enum

index
INTERMEDIATE

An enum is a kind of class. It has a superclass, Enum, from which it inherits some methods. An enum has all the features of an "ordinary" class (fields, constructors, methods, etc.), except that an enum has a fixed, finite number of instances (objects) of the class, defined directly within the class itself. In other words, when you define an enum, you also define all its possible values, and you cannot later create additional values.

An enum is appropriate when you need a variable that represents one of a fixed set of values--for example, the months of a year. They provide type safety: You cannot, for instance, assign a Coin value to a Month variable.

The simplest form of enum consists of a list of constants, each of which is one of the values of the enum. For example,

enum Weekday { SUN, MON, TUE, WED, THU, FRI, SAT }

This example defines the type Weekday and seven instances (values) of that type. Each of these is a unique constant. Because they are unique, they can be compared with == as well as with the equals method.

In the Weekday example, each of the instances (SUN, MON, etc.) has been created by (implicitly) calling the default Weekday constructor. As with any class, you can write your own constructors; however, (1) those constructors will be private, and (2) you call them, not by saying new, but by giving the instance name followed by a parameter list. For example,

public enum Coin {
    private final int value; // A field
 
    Coin(int value) { this.value = value; } // The constructor
 
    PENNY(1), NICKEL(5), DIME(10), QUARTER(25); // The instances
 
    public int value() { return value; } // A method
}

Some methods you can use with enumerations are: