枚举
jdk1.5以后引入
关键字 enmu
enmu Apple{ Jonathan, GoldenDel, RedDel
}
枚举常量被隐式声明为Apple的公有静态 final成员
枚举能够定义类类型,但却不能使用new实例化一个枚举
AppleAp;
Ap=Apple.RedDel;
两枚举常量可以用“==”比较
if(Ap== Apple.RedDel)
枚举值可用于控制switch语句
switch(Ap){
case RedDel:
case GoldenDe l:
}
两种方法values() value of()
values() 返回包含一列枚举常量的数组 , value of() 返回一个 两种方法
Appleaps [ ]=Apple.values;
Ap=Apple.valueof(“Jonathan ”);
for-each风格
for(Apple a:Apple.values() ){}
java枚举是类类型
可以定义枚举的构造函数建立每一个枚举常量时调用该构造函数
enmu Apple{ Jonathan(10), GoldenDel(16), RedDel (8)
private int price;
Apple ( intp) { price=p; }
int getPrice(){
return price;
}
}
枚举支持重载
enmu Apple{ Jonathan(10), GoldenDel, RedDel (8)
private int price;
Apple ( intp) { price=p; }
Apple ( ) { price=0; }
int getPrice(){
return price;
}
}
枚举有两个限制 1不能继承另一个类。2 不能是超类不能被扩展
枚举继承 Enum
枚举几个常用方法
ordinal()
compareTo()
equals()