講述java中enum的用法
本文實(shí)例講述了java中enum的用法。分享給大家供大家參考。具體分析如下:
1. 基本用法
復(fù)制代碼 代碼如下:enum Day {
SUNDAY, MONDAY, TUESDAY, WENDSDAY, THURSDAY, FRIDAY, SATURDAY;
}
枚舉是常量,所以應(yīng)該用大寫。
2. 枚舉是對象
枚舉隱含地繼承了java.lang.Enum,所以它具有java.lang.Enum的.屬性和方法。遍歷枚舉:
復(fù)制代碼 代碼如下:public class Main {
public static void main(String[] args) {
for(Day day:Day.values()) {
System.out.println(day);
}
}
}
3. 枚舉可以帶字段和方法,以下示例來自官方The Java Tutorials
復(fù)制代碼 代碼如下:public enum EnumDemo {
AOBJECT("field one", "field two");
private String field1;
private String field2;
EnumDemo(String val1, String val2){
this.field1 = val1;
this.field2 = val2;
}
public void printFields(){
System.out.println(this.field1);
System.out.println(this.field2);
}
public static void main(String[] args) {
EnumDemo.AOBJECT.printFields();
}
}
以下現(xiàn)實(shí)中的示例來自官方的Java Tutorial:
復(fù)制代碼 代碼如下:public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
Double earthWeight = 120;
for(Planet p: Planet.values()){
System.out.println(p.surfaceGravity());
System.out.println(p.surfaceWeight(earthWeight/EARTH.surfaceGravity()));
}
}
}
4. 枚舉是singleton,可以用枚舉來構(gòu)建一個Singleton
復(fù)制代碼 代碼如下:public enum Singleton {
INSTANCE(new String[]{"arg1", "arg2"});
String[] myArgs;
Singleton(String[] args){
this.myArgs = args;
}
public static Singleton getInstance(){
return INSTANCE;
}
public static void main(String[] args) {
for(String arg : INSTANCE.myArgs)
System.out.println(arg);
}
}
【講述java中enum的用法】相關(guān)文章: