package yuwei.com;
/*1
* 枚举类通常应该设计成不可变类,也就是说
* 它的成员变量值不应该改变,这样会更加的安全
* 而且代码会更加简单,因此枚举类的成员变量都使用private final 修饰
* 但此时类里应有构造函数,并为枚举值设置初始值
* */
/*2
* 实现接口的枚举类*/
interface GenderDesc{
void info();
}
enum Gender implements GenderDesc{
Red("红"){
public void info() {
System.out.println("RED 代表红颜色");
}
}
,GREEN("绿"){
public void info() {
System.out.println("GREEN 代表绿颜色");
}
};
//定义一个public修饰的实例变量
private final String color;
public String getColor() {
return color;
}
Gender(String color) {
this.color = color;
}
}
/*3
* 包含抽象方法的枚举类*/
enum Calute{
PLUS{
@Override
public double opear(double x, double y) {
// TODO Auto-generated method stub
return x + y;
}
},
MINUS{
@Override
public double opear(double x, double y) {
// TODO Auto-generated method stub
return x-y;
}
};
public abstract double opear(double x,double y);
}
public class EnumDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//通过Enum的valueOf()方法来获取指定枚举类的枚举值
Gender g = Enum.valueOf(Gender.class,"Red");
System.out.println( Gender.GREEN.getColor() );
System.out.println(g + "代表:" + g.getColor());
g.info();
//遍历所有的枚举
for( Gender temp : Gender.values()){
System.out.println( temp + " name: " + temp.getColor() );
}
//
System.out.println(Calute.PLUS.opear(9, 5));
}
}
枚举类
最新推荐文章于 2022-07-16 10:28:46 发布