Java 枚举类型

Enum Types

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

枚举(enum)类型是一种特殊的数据类型,它允许变量是一组预定义的常量。该变量必须等于为其预定义的值之一。常见的例子包括指南针方向(NORTH、SOUTH、EAST、WEST 的值)和星期。

Because they are constants, the names of an enum type’s fields are in uppercase letters.

因为它们是常量,所以枚举类型的字段名称使用大写字母。

In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:

在 Java 编程语言中,通过使用 enum 关键字定义枚举类型。例如,您可以指定一个星期的枚举类型为:

public enum Day {
    SUNDAY, // 星期日
    MONDAY, // 星期一
    TUESDAY, // 星期二
    WEDNESDAY, // 星期三
    THURSDAY, // 星期四
    FRIDAY, // 星期五
    SATURDAY // 星期六
}

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

在需要表示一组固定的常量时,应该使用枚举类型。这包括自然枚举类型,如太阳系中的行星,以及在编译时知道所有可能值的数据集 —— 例如,菜单上的选项、命令行标志等等。

Here is some code that shows you how to use the Day enum defined above:

这里是一些代码,告诉你如何使用上文定义的 Day 枚举:

public class EnumTest {
    Day day;
    
    public EnumTest(Day day) {
        this.day = day;
    }
    
    /**
     * <p> 坦白说;实事求是地说
     */
    public void tellItLikeItIs() {
        switch (day) {
        case MONDAY:
            System.out.println("Mondays are bad. 星期一是坏的。");
            break;
        case FRIDAY:
            System.out.println("Fridays are better. 星期五更好。");
            break;
        case SATURDAY:
        case SUNDAY:
            System.out.println("Weekends are best. 周末是最好的。");
            break;
        default:
            System.out.println("Midweek days are so-so. 周中的日子一般般。");
            break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        
        EnumTest sevenDay = new EnumTest(Day.SUNDAY);
        sevenDay.tellItLikeItIs();
    }
}

The output is:

Mondays are bad. 星期一是坏的。
Midweek days are so-so. 周中的日子一般般。
Fridays are better. 星期五更好。
Weekends are best. 周末是最好的。
Weekends are best. 周末是最好的。

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

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));
}

Note: All enums implicitly extend java.lang.Enum. Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.

注意:所有枚举都隐式地继承自 java.lang.Enum。因为一个类只能继承自一个父类(请参 Declaring Classes),所以 Java 语言不支持状态的多重继承(请参阅 Multiple Inheritance of State, Implementation, and Type),因此集成不能继承自任何其他东西。


In the following example, Planet is an enum type that represents the planets in the solar system. They are defined with constant mass and radius properties.

在下面的例子中,Planet 是一个枚举类型,表示太阳系中的行星。它们被定义为具有质量和半径属性。

Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.

每个枚举常量都用质量和半径参数的值声明。这些值在创建常量时传递给构造方法。Java 要求首先定义常量,然后才是任何字段或方法。此外,当有字段和方法时,枚举常量列表必须以分号结束。


Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

注意:枚举类型的构造方法必须是包私有或私有访问的。它自动创建在枚举主体开头定义的常量。您不能自己调用枚举构造方法。


In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

除了它的属性和构造方法外,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; // 单位:质量
    private final double radius; // 单位:米

    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;
        double mass = earthWeight / EARTH.surfaceGravity();
        for (Planet p : Planet.values())
            System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass));
    }
}

输出:

Your weight on MERCURY is 45.330914
Your weight on VENUS is 108.599892
Your weight on EARTH is 120.000000
Your weight on MARS is 45.448462
Your weight on JUPITER is 303.666903
Your weight on SATURN is 127.921865
Your weight on URANUS is 108.615264
Your weight on NEPTUNE is 136.599369
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值