Documentation

The Java™ Tutorials
Hide TOC
Enum Types枚举类型
Trail: Learning the Java Language
Lesson: Classes and Objects

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.常见的示例包括指南针方向(北、南、东和西的值)和一周中的几天。

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.在Java编程语言中,可以使用enum关键字定义枚举类型。For example, you would specify a days-of-the-week enum type as:例如,您可以将每周天数枚举类型指定为:

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;
    }
    
    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 seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.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.Java编程语言枚举类型比其他语言中的枚举类型强大得多。The enum declaration defines a class (called an enum type).enum声明定义了一个(称为枚举类型)。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.例如,它们有一个静态value方法,该方法返回一个数组,该数组按声明的顺序包含枚举的所有值。This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.此方法通常与for-each构造结合使用,以迭代枚举类型的值。For example, this code from the Planet class example below iterates over all the planets in the solar system.例如,下面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.所有枚举都隐式扩展java.lang.EnumBecause 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语言不支持状态的多重继承(请参见状态、实现和类型的多重继承),因此枚举不能扩展任何其他内容。

In the following example, Planet is an enum type that represents the planets in the solar system.在以下示例中,Planet是表示太阳系中行星的枚举类型。They are defined with constant mass and radius properties.它们使用恒定质量和半径特性定义。

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.Java要求在任何字段或方法之前首先定义常量。Also, when there are fields and methods, the list of enum constants must end with a semicolon.此外,当存在字段和方法时,枚举常量列表必须以分号结尾。


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.除了属性和构造器外,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):下面是一个示例程序,它可以测量你在地球上的体重(以任何单位表示),并计算和打印你在所有行星上的体重(以相同单位表示):

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

If you run Planet.class from the command line with an argument of 175, you get this output:如果从命令行运行参数为175的Planet.class,则会得到以下输出:

$ 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

Previous page: Questions and Exercises: Nested Classes
Next page: Questions and Exercises: Enum Types