---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ---------------------
枚举就是要让某个类型的变量的取值只能为若干个固定值中的一个,否则,编译器报错
枚举是一种特殊的类,不是接口,它的枚举值都是一个枚举类型的实例。
枚举的基本应用
public class EnumTest2 {
public enum WeekDay{
SUN,MON,TUE,WED,THI,FRI,SAT;
}
public static void main(String[] args) {
WeekDay weekDay = WeekDay.FRI;
System.out.println(weekDay);
System.out.println(weekDay.name());
System.out.println(weekDay.ordinal());
System.out.println(WeekDay.valueOf("SUN"));
//valueOf()方法返回与以字符串形式表示的常量名称相关联的枚举值。
System.out.println(WeekDay.values().length);
}
}
实现带有构造方法的枚举
public class EnumTest3 {
public enum WeekDay{
SUN(1),MON(),TUE,WED,THI,FRI,SAT;
private WeekDay()
{
System.out.println("first");
}
private WeekDay(int Day)
{
System.out.println("second");
}
}
public static void main(String[] args) {
WeekDay weekDay = WeekDay.FRI;
System.out.println(weekDay);
System.out.println(weekDay.name());
System.out.println(weekDay.ordinal());
System.out.println(WeekDay.valueOf("SUN").toString());
//valueOf()方法返回与以字符串形式表示的常量名称相关联的枚举值。
System.out.println(WeekDay.values().length);
}
}
实现带有抽象方法的枚举
带方法的枚举
1.定义枚举TrafficLamp
2.实现普通的next方法
3.实现抽象的next方法:每个元素分别是由枚举的子类来生成的实例对象,这些子类采用类似内部类的方式进行定义
4.增加表示时间的构造方法
枚举只有一个成员时,就可以作为一种单例的实现方式。
public class EnumTest4 {
public enum TrafficLamp{
RED(30){
public TrafficLamp nextLamp()
{
return GREEN;
}
},
GREEN(50){
public TrafficLamp nextLamp()
{
return YELLOW;
}
},
YELLOW(5){
public TrafficLamp nextLamp()
{
return RED;
}
};
public abstract TrafficLamp nextLamp();
private int time;
private TrafficLamp(int time)
{
this.time = time;
}
}
public static void main(String[] args) {
TrafficLamp tl = TrafficLamp.GREEN;
System.out.println(tl.nextLamp());
}
}
-----------------------ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------
详细请查看:http://edu.csdn.net