枚举类
枚举就是要使到某个变量的取值只能是程序员自己定义的固定值之中的一个。取到其他的值则会编译出错。
枚举的原理:(如代码所示)
package Enum;
public class WeekDay {
private WeekDay(){}; //类定义成为私有类型,即外部不能实例化这个WeekDay 类
public static final WeekDay Mon=new WeekDay(); //把这个成员变量定义为 static (静态) 与final (固定使到子类不能继承).
public final static WeekDay Tus =new WeekDay(); //static 与final 谁先谁后都可以的
public String toString(){
return this==Mon?Mon:Tus; //返回字符串
}
自已总结:
1.枚举类似于单例模式,由几个独立的单例模式组成的类。
2.枚举类必须是私有,即外面是不能私有化它的,不过它的成员变量是已经实例化的(即new 过的);
3.toString 方法在枚举类里面是要自己定义的,不过在enum类里面是封装起来的,即enum是把上面那些都封装起来了。
枚举类:
public enum WeekDay{
Mon,Tus(100);
private WeekDay(){System.out.println("Mon 会调用无参构造方法");};
private WeekDay(int i){System.out.println("Tus 会调用有参方法");};
}
总结:1.构造方法必须是私有的;
2.成员变量会调用WeekDay的构造方法,如在主函数中定义WeekDay.Mon;时,则会两个构造方法都会调用。
练习:
public abstract trafficLamp{
private trafficLamp(int i){}; //1.调用有参的构造方法
public final static trafficLamp red=new trafficLamp(5){ //匿名内部类,是子类来的,1.实现有构造方法的,2实现nextLamp()方法的;
public trafficLamp nextLamp(){
return green;
}
};
public final static trafficLamp green=new trafficLamp()(10){
public trafficLamp nextLamp(){
return red;
}
};
public abstract trafficLamp nextLamp(); //2.定义父类的抽象方法,子类必须实现
}
如果用正式枚举:
public enum trafficLamp{
red(10){
public trafficLamp nextLamp11(){
return green;
}
},
green(45){
public trafficLamp nextLamp11(){
return yellow;
}
},yellow(5){
@Override
public trafficLamp nextLamp11() {
// TODO 自动生成的方法存根
return red;
}
};
private int time;
private trafficLamp(int time){ //1.构造方法
time=time;
}
public abstract trafficLamp nextLamp11(); //2.抽象方法
}
}
基础知识:
1.匿名内部类
2.抽象方法私有
3.<red,green,yellow>枚举声明可以显式地声明 byte、sbyte、short、ushort、int、uint、long 或 ulong 类型作为对应的基础类型。没有显式地声明基础类型的枚举声明意味着所对应的基础类型是 int。
在枚举类型中声明的第一个枚举成员它的默值为零。 以后的枚举成员值是将前一个枚举成员(按照文本顺序)的值加 1 得到的。
int (red 1, green 2, yellow 3)