Java筆記 列舉的用法

2021-06-22 08:02:16 字數 1405 閱讀 5046

列舉的用法

[一] switch語句以及列舉自帶的屬性

此處要注意switch(引數)引數型別只能是byte,short,char,int和列舉型別,float,double,string型別都不可以。

public class enumexample 

public static void main(string args)

// 列舉的遍歷;輸出結果 red green yellow blue

for (colorenum color : colorenum.values())

// 列舉的個數;輸出的結果 colorenum列舉中的值的個數:4

system.out.println("colorenum列舉中的值的個數:" + colorenum.values().length);

// 列舉中索引的位置,預設從0開始;輸出的結果 0 1 2

system.out.println(colorenum.red.ordinal());

system.out.println(colorenum.green.ordinal());

system.out.println(colorenum.yellow.ordinal());

}}

[二]列舉類似「類」的用法

可以寫成員變數,構造方法以及方法。其中需要注意,這些必須寫在列舉之後,而且列舉必須以分號結束。(如果只是單純的寫列舉常量,分號可省略)。同時列舉的構造方法必須是private,保證構造方法只在內部使用。

public class enumexample 

// 構造方法過載

private colorenum(string name)

// getter setter

public string getname()

public void setname(string name)

// 自定義方法

public static colorenum getnames()

} public static void main(string args)

}

結果是:

過載的構造方法

過載的構造方法

空構造方法

空構造方法

紅色[三]帶有抽象方法的列舉

public class enumexample 

},green

},yellow

},blue

};public abstract string getname();

} public static void main(string args)

}

結果是:紅色

其他作用:也可以實現介面

JAVA列舉型別用法二

要將列舉放在乙個單獨的class檔案裡 如下 注意要有構造方法,up裡面既可以寫字串,也可以寫整型。package test.testenum public enum yihongyuanenum private yihongyuanenum string oldmodestr 在類getspeci...

Java學習筆記 列舉

public class testenum class color1第二種方式public class testenum class color2 public static final color2 red new color2 紅燈亮為1 public static final color2 g...

java學習筆記 列舉類

列舉法本質其實就是乙個類 一 常量的使用 public classenumerationelse for inti 0 i a.length i if a i getindex num system.out println 您需要付款 a i getprice num2 列舉法本質就是類,它的構造方...