Skip Top Navigation Bar

enum Constructors and Methods

enum Recap

An enum is a type of class. It represents a group of named constants. They are used when we know all the possible values, such as in the example of the directions for the robot. Other examples might include:

Learn more:

Constructors

There are times when we want values to be associated with the different constants of an enum. For example, if we have directions for a robot of NORTH, SOUTH, EAST, and WEST, we may also want to include the number of degrees represented by each of these. Since enum is a type of class, it can include instance variables, constructors, and methods. The associate degree values are tied to the directions. We can include an instance variable called degrees and have a constructor that will assign degrees to the corresponding values.

General Format

enum NameOfEnum {
    CONSTANT1(value1, value2, ...),
    CONSTANT2(value1, value2, ...),
    ...
    CONSTANTX(value1, value2, ...);

    <datatype> myvar1;
    <datatype> myvar2;
    ...
    <datatype> myvarx;

    NameOfEnum(<datatype> var1, <datatype> var2, ... <datatype> varx) {
        myvar1 = var1;
        myvar2 = var2; 
        ...
        myvarx = varx;
    }
}

Methods

You can also add accessor, mutator, and other methods to the enum.

Class Creation

Your Turn