獻給我老公 - Java枚舉類型


枚舉類型是一種特殊的數據類型。具有枚舉類型的變量,其取值范圍會被限定在預定義的常量池中。該變量的值必須為預定義取值的其中之一。常見的例子有指南針的方向(東,西,南,北)和星期幾。

由於是常量,枚舉類型中定義的字段均為大寫字母。

在Java編程語言中,通過關鍵字 enum 來定義一個枚舉類型。例如,定義一個一周有幾天的枚舉類型:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

在任何需要定義一個限定常量池的場景下,你就需要用到枚舉類型。這包括自然界的枚舉類型,例如銀河系的星球,編譯時就知道所有取值情況的數據集合——例如,一個菜單的選項,命令行標記等等。

這里給出一個以上定義的Day枚舉類型應用實例:

public class EnumTest {
    Day day;
    
    public EnumTest(Day day) {
        this.day = day;
    }
    
    public void tellTheTruth() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad if my husband is not around.");
                break;
                    
            case FRIDAY:
                System.out.println("Fridays are better if my husband could have dinner with me.");
                break;
                         
            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best if my husband is by my side.");
                break;
                        
            default:
                System.out.println("Midweek days are good if my husband is able to have lunch with me.");
                break;
        }
    }
    
    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellTheTruth();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellTheTruth();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellTheTruth();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellTheTruth();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellTheTruth();
    }
}

輸出為:

Mondays are bad if my husband is not around.
Midweek days are good if my husband is able to have lunch with me.
Fridays are better if my husband could have dinner with me.
Weekends are best if my husband is by my side.
Weekends are best if my husband is by my side.

 

Java編程語言中的枚舉類型比其他語言中的同種類型更為強大。enum在聲明時定義了一個類(稱為一個枚舉類型)。枚舉類可以包含方法以及其他屬性。在創建一個枚舉時編譯器會自動添加一些特殊方法。例如,它們都有一個靜態的 values 方法,這個方法會按定義時的順序返回枚舉中的所有值。這個方法常與 for-each 連用以遍歷一個枚舉類型中的所有值。例如,下面這段選自 Planet 類的代碼遍歷了太陽系的所有星球。

for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
}

注意: 所有枚舉隱式繼承  java.lang.Enum. 由於一個類只能有一個父類,Java語言不支持多繼承,所以枚舉不能繼承其他類。

在接下來的例子中,Planet 是一個表示太陽系中所有星球的枚舉類型。它們在定義時加入了體積和半徑常量作為其屬性。

每個枚舉常量在聲明時都有體積和半徑作參數。在常量創建時這些值將被傳入構造方法。Java要求先定義常量,優先於其他字段或者方法。並且當有其他字段和方法存在時,枚舉常量列表必須以分號結尾。


注意: 枚舉類型的構造方法必須定義為包私有或私有訪問級別。它會自動創建定義在類體前部的常量。構造方法不能被手動調用。

除了屬性和構造方法,Planet還提供了獲取星球上表面重力和物體質量的方法。這里給出一個樣例程序,以地球上的質量(任意單位)為入參,計算其在其他星球上的質量(相同單位):

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) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

如果從命令行運行Planet.class並且輸入參數175,會得到以下輸出:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com