Emun是java1.5新增的内容,它和class与interface在java中的地位是一样的,只是三种应用场景不一样,它的出现是为了简便我们对常量和固定类的调用
Emun类的用途:
1,类的个数是有限的且是固定的
2,对一个或一组常量的定义
Emun类的特性:
1,Emun默认继承java.lang.Enum类,而不是object类
2,Emun的所有对象实例,都默认被添加了public static final
3,Emun的构造方法是private的,不能被外部实例化
4,Emun不能继承,但可以多接口实现
5,Emun类不能被继承
自定义枚举类:
emun类其实也是对类的封装,只是它自己给了我们一个模板
public class customemun {
//定义属性
private final String WQL;
private final String FQ;
//私有化构造方法
private customemun(String WQL,String FQ){
this.WQL=WQL;
this.FQ=FQ;
}
public String getWQL() {
return WQL;
}
public String getFQ() {
return FQ;
}
//提供枚举对象实例
static final customemun ONE=new customemun("晴天","LOVE");
static final customemun TWO=new customemun("雨天","DISLIVE");
@Override
public String toString() {
return "customemun [WQL=" + WQL + ", FQ=" + FQ + "]";
}
}
一,Emun类的使用
一,语法规范
1,枚举类的枚举实例只能在类的最前面
2,多个枚举实例中间有逗号( , )隔开,结尾用分号( ; )结束
//正确写法
public enum emunwql {
WQL,
FQ;
private int a;
private String b;}
//错误写法
public enum emunwql {
private int a;
private String b;
WQL;
FQ;
}
二,构造方法和toString方法
枚举类的实例是本类的实现,系统默认是以public static final修饰
public enum emunwql {
//枚举对象实例
WQL(1,"LOVE"),
FQ(2,"FQ");
private int a;
private String b;
//构造方法
private emunwql(int a,String b) {
this.a=a;
this.b=b;
}
public int getA() {
return a;
}
public String getB() {
return b;
}
//重写toString方法,这不是object的,而是Emun类的
@Override
public String toString() {
return a+"--"+b;
}
}
测试:
public class test1 {
public static void main(String[] args) {
System.out.println(emunwql.WQL);
System.out.println(emunwql.WQL.getA());
}
}
输出:
1--LOVE
1





Comments | NOTHING