【給小白看的Java教程】第二十六章,可勝列舉:列舉
###列舉的誕生歷史(瞭解)
在服裝行業,衣服的分類根據性別可以表示為三種情況:男裝、女裝、中性服裝。
private ? type;
public void setType(? type){
this.type = type
}
需求:定義一個變數來表示服裝的分類?請問該變數的型別使用什麼? 使用int和String型別,且先假設使用int型別,因為分類情況是固定的,為了防止呼叫者亂建立型別,可以把三種情況使用常量來表示。
public class ClothType { public static final int MEN = 0; public static final int WOMEN = 1; public static final int NEUTRAL = 2; }
注意:常量使用final修飾,並且使用大小字面組成,如果是多個單片語成,使用下劃線分割。 此時呼叫setType方法傳遞的值應該是ClothType類中三個常量之一。但是此時依然存在一個問題——依然可以亂傳入引數比如100,此時就不合理了。 同理如果使用String型別,還是可以亂設定資料。那麼說明使用int或String是型別不安全的。那麼如果使用物件來表示三種情況呢?
public class ClothType { public static final ClothType MEN = new ClothType(); public static final ClothType WOMEN = new ClothType(); public static final ClothType NEUTRAL = new ClothType(); }
此時呼叫setType確實只能傳入ClothType型別的物件,但是依然不安全,為什麼?因為呼叫者可以自行建立一個ClothType物件,如:setType(new ClothType)。 此時為了防止呼叫者私自創建出新的物件,我們把CLothType的構造器私有化起來,外界就訪問不了了,此時呼叫setType方法只能傳入ClothType類中的三個常量。此時程式碼變成:
public class ClothType { public static final ClothType MEN = new ClothType(); public static final ClothType WOMEN = new ClothType(); public static final ClothType NEUTRAL = new ClothType(); private ClothType() {} }
高,實在是高!就是程式碼複雜了點,如果存在定義這種型別安全的且物件數量固定的類的語法,再簡單點就更好了——有列舉類。 13.7.2.列舉類的定義和使用(掌握) 列舉是一種特殊的類,固定的一個類只能有哪些物件,定義格式:
public enum 列舉類名{
常量物件A, 常量物件B, 常量物件C ;
}
我們自定義的列舉類在底層都是直接繼承了java.lang.Enum類的。
public enum ClothType {
MEN, WOMEN, NEUTRAL;
}
列舉中都是全域性公共的靜態常量,可以直接使用列舉類名呼叫。
ClothType type = ClothType.MEN;
因為java.lang.Enum類是所有列舉類的父類,所以所有的列舉物件可以呼叫Enum類中的方法.
String name = 列舉物件.name(); // 返回列舉物件的常量名稱
int ordinal = 列舉物件.ordinal(); // 返回列舉物件的序號,從0開始
注意:列舉類不能使用建立物件
public class EnumDemo {
public static void main(String[] args) {
int ordinal = ClothType.MEN.ordinal();
String name = ClothType.MEN.name();
System.out.println(ordinal);
System.out.println(name);
new ClothType(); //語法報錯
}
}
目前,會定義列舉類和基本使用就可以了,後面還會講更高階的使用方式。
若要獲得最好的學習效果,需要配合對應教學視訊一起學習。需要完整教學視訊,請參看https://ke.qq.com/course/272077。