Java列舉型別
一、列舉定義
列舉不能定義在靜態方法中
一般自定義的列舉型別都屬於Enum的子型別EnumType
它預設就有兩個靜態方法(類方法):values()和valueOf()
values()返回的是EnumType型別的例項陣列
valueOf()返回的是EnumType型別的例項
二、舉例:自定義Color列舉型別
Color{ WHITE, BLACK, GRAY }
Color c = Color.GRAY;
那麼:
Color.valueOf("BLACK") == Color.BLACK == Color.values()[1]
因為它們返回的都是Color型別
c.toString() == c.name()
因為它們返回的是字串
三、列舉的建構函式和成員變數
列舉的建構函式只能是private
列舉的成員變數則不受限制,但如果在列舉例項裡面定義的方法需要訪問列舉型別中的成員變數,則該成員變數至少要是protected,否則無法繼承
package newpack17;
interface d{
public String getDescription();
public int getI();
}
public enum AnyEnum implements d{
Constants_A{
public String getDescription() {
return "我是列舉成員A";
}
public int getI() {
return i;
}
},
Constants_B{
public String getDescription() {
return "我是列舉成員B";
}
public int getI() {
return i;
}
},
Constants_E("列舉成員E",88){
public String getDescription() {
return this.str;
}
public int getI() {
return this.it;
}
},
Constants_C,
Constants_D{
public String getDescription() {
return "我是列舉成員D";
}
public int getI() {
return i;
}
};
private AnyEnum(String str,int i) {
this.str = str;
this.it=i;
}
private AnyEnum() {}
public String getDescription() {
return "我是列舉成員XXX";
}
public int getI() {
return 10000;
}
public int it; // protected也行,但不能是private
protected String str;
private static int i = 5; // 靜態成員 public protected,private都行
public static void main(String[] args) {
for(int i = 0; iSystem.out.println(AnyEnum.values()[i]+"呼叫getDescription()方法為:"+AnyEnum.values()[i].getDescription());
System.out.println(AnyEnum.values()[i]+"呼叫getI()方法為:"+AnyEnum.values()[i].getI());
}
}
}
為了讓學習變得輕鬆、高效,今天給大家免費分享一套Java教學資源。幫助大家在成為Java架構師的道路上披荊斬棘。需要資料的歡迎加入學習交流群:9285,05736