枚举
枚举是由class来实现的(继承Enum类,所以不能再继承其他类,也不能被继承,但是可用来实现接口)。因此由enum可以实现很多class的内容,包括可以有member和member function
1.常量
public enum Color{
RED,
GREEN,
BLANK,
YELLOW
}
2.switch
Color color=new Color();
switch(color){
case RED:
break;
case GREEN:
break;
case YELLOW:
break;
case BLANK:
break;
case YELLOW:
break;
}
3.方法
public enum Color{
RED,
GREEN,
BLANK,
YELLOW
private String name;
private int index;
private Color(String name,int index){
this.name=name;
this.index=index;
}
public void setName(String name){
this.name=name;
}
public void setIndex(int index){
this. index=index;
}
public String getName(){
return name;
}
public int getIndex(){
return index;
}
}
4.覆盖枚举中的方法
public enum Color{
RED,
GREEN,
BLANK,
YELLOW
private String name;
private int index;
private Color(String name,int index){
this.name=name;
this.index=index;
}
public void setName(String name){
this.name=name;
}
public void setIndex(int index){
this. index=index;
}
public String getName(){
return name;
}
public int getIndex(){
return index;
}
@override
public String toString(){
return this.index+" "+this.name;
}
}
5.实现接口
public interface Behaviour{
void print();
}
public enum Color implements Behaviour{
RED,
GREEN,
BLANK,
YELLOW
private String name;
private int index;
private Color(String name,int index){
this.name=name;
this.index=index;
}
public void setName(String name){
this.name=name;
}
public void setIndex(int index){
this. index=index;
}
public String getName(){
return name;
}
public int getIndex(){
return index;
}
@override
public String toString(){
return this.index+" "+this.name;
}
@override
public void print(){
System.out.println(this.toString());
}
}
6.使用接口组织枚举
public interface Food{
enum Coffee implements Food{
BLACK_COFFEE,DECAF_COFFEE
}
}
7.枚举集合
EnumSet、EnumMap