java枚舉類的構(gòu)造函數(shù)實例詳解
java枚舉類的構(gòu)造函數(shù)實例詳解
首先,給出一個例題如下:
enum AccountType
{
SAVING, FIXED, CURRENT;
private AccountType()
{
System.out.println(“It is a account type”);
}
}
class EnumOne
{
public static void main(String[]args)
{
System.out.println(AccountType.FIXED);
}
}
Terminal輸出:
It is a account type It is a account type It is a account type FIXED
分析:
創(chuàng)建枚舉類型要使用 enum 關(guān)鍵字,隱含了所創(chuàng)建的類型都是 Java.lang.Enum 類的子類(java.lang.Enum 是一個抽象類)。枚舉類型符合通用模式Class Enum<E extends Enum <E>>,而E表示枚舉類型的名稱的每一個值都將映射到 protected Enum(String name, int ordinal) 構(gòu)造函數(shù)中
簡單來說就是枚舉類型中的枚舉值都會對應(yīng)調(diào)用一次構(gòu)造函數(shù),本題中三個枚舉值,這里還要特別強調(diào)一下,枚舉中的構(gòu)造函數(shù)是私有類,也就是無法再外面創(chuàng)建enum
枚舉值默認static(靜態(tài)類常量) ,會為每個類常量增加一個構(gòu)造函數(shù)。AccountType.FIXED使用的是枚舉值,沒有創(chuàng)建。所以一共就3次。
public class Test {
public static void main(String[] args) {
weekday mon = weekday.mon;
weekday tue = weekday.tue;
weekday thus = weekday.thus;
weekday fri = weekday.fri;
}
public enum weekday {
mon(), tue(2), wes(3), thus(), fri;
private weekday() {
System.out.println("no args");
}
private weekday(int i) {
System.out.println("have args " + i);
};
}
}
Terminal輸出:
no args have args 2 have args 3 no args no args
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
java使用@Scheduled注解執(zhí)行定時任務(wù)
這篇文章主要給大家介紹了關(guān)于java使用@Scheduled注解執(zhí)行定時任務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
springboot websocket集群(stomp協(xié)議)連接時候傳遞參數(shù)
這篇文章主要介紹了springboot websocket集群(stomp協(xié)議)連接時候傳遞參數(shù),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07

