练习一
案例:使用枚举类实现单例模式
package chapter08_oop3_teacher.src.com.atguigu10._enum.exer1;
/**
* ClassName: BankTest1
* Description:
*
* @Author 尚硅谷-宋红康
* @Create 15:05
* @Version 1.0
*/
public class BankTest1 {
public static void main(String[] args) {
// Bank1.instance = null;
System.out.println(GirlFriend.XIAO_LI);
}
}
//jdk5.0之前的使用枚举类定义单例模式
class Bank1{
private Bank1(){}
public static final Bank1 instance = new Bank1();
}
//jdk5.0使用enum关键字定义枚举类的方式定义单例模式
enum Bank2{
CPB;
}
enum GirlFriend{
XIAO_LI(20);
private final int age;
private GirlFriend(int age){
this.age = age;
}
}
练习二
案例:颜色枚举类Color(使用enum声明)
1、声明颜色枚举类:7个常量对象:RED, ORANGE, YELLOW, GREEN, CYAN, BLUE,PURPLE;
2、在测试类中,使用枚举类,获取绿色对象,并打印对象。
package chapter08_oop3_teacher.src.com.atguigu10._enum.exer2;
/**
* ClassName: Color
* Description:
*
* @Author 尚硅谷-宋红康
* @Create 15:12
* @Version 1.0
*/
public enum Color {
RED, ORANGE, YELLOW, GREEN, CYAN, BLUE,PURPLE;
}
练习三
案例拓展:颜色枚举类(使用enum声明)
(1)声明颜色枚举类Color:
- 声明final修饰的int类型的属性red,green,blue
- 声明final修饰的String类型的属性description
- 声明有参构造器Color(int red, int green, int blue,String description)
- 创建7个常量对象:红、橙、黄、绿、青、蓝、紫,
- 重写toString方法,例如:RED(255,0,0)->红色
(2)在测试类中,使用枚举类,获取绿色对象,并打印对象。
提示:
- 7个常量对象的RGB值如下:
红:(255,0,0)
橙:(255,128,0)
黄:(255,255,0)
绿:(0,255,0)
青:(0,255,255)
蓝:(0,0,255)
紫:(128,0,255)
7个常量对象名如下:
RED, ORANGE, YELLOW, GREEN, CYAN, BLUE,PURPLE
package chapter08_oop3_teacher.src.com.atguigu10._enum.exer3;
/**
* ClassName: ColorTest
* Description:
*
* @Author 尚硅谷-宋红康
* @Create 15:14
* @Version 1.0
*/
public class ColorTest {
public static void main(String[] args) {
System.out.println(Color.GREEN);
}
}
enum Color{
RED(255,0,0,"红色"),
ORANGE(255,128,0,"橙色"),
YELLOW(255,255,0,"黄色"),
GREEN(0,255,0,"绿色"),
CYAN(0,255,255,"青色"),
BLUE(0,0,255,"蓝色"),
PURPLE(128,0,255,"紫色");
private final int red;
private final int green;
private final int blue;
private final String description;//颜色的描述
Color(int red, int green, int blue, String description) {
this.red = red;
this.green = green;
this.blue = blue;
this.description = description;
}
public int getRed() {
return red;
}
public int getGreen() {
return green;
}
public int getBlue() {
return blue;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
// return name() + "(" + red + "," + green + "," + blue + ")->" + description;
return super.toString() + "(" + red + "," + green + "," + blue + ")->" + description;
}
}