About enum

As of Java 5, Java lets developers restrict a variable to having one of only a few predefined values – in other words, one value of an enumerated list.

Enum can be declared as top-level class, and also as inner class. Enums cannot be declared in methods. Java language designers made it optional to put a semicolon at the end of the enum declaration.

Basic components of enum are constants. It is not required that enum constants be in all caps, but Oracle convention assume constants to be completely caps.

Enum is a kind of a class that looks something (but not exactly) like this:

enum concept
enum CoffeeSize {BIG, HUGE, OVERWHELMING}

// можно представить примерно так:

class CoffeeSize {

public static final CoffeeSize BIG =
new CoffeeSize(“BIG”, 0);
public static final CoffeeSize HUGE =
new CoffeeSize(“HUGE”, 1);
public static final CoffeeSize OVERWHELMING =
new CoffeeSize(“OVERWHELMING”, 2);

CoffeeSize(String enumName, int index) {
// stuff here
}

public static void main(String[] args) {
System.out.println(CoffeeSize.BIG);
}

}

Each of enumerated values (declared as public static final) is an instance of type CoffeeSize. Also each enum value has its index position – in other words, the order in which enum values are declared matters. You can think of the CoffeeSize enums as existing in an array of type CoffeeSize, and you can iterate through the values of an enum by invoking static values() method.

Enums can have constructors, properties, methods and so called canstant specific class body. Enum constructor cannot be invoked directly. It is invoked automatically. with the arguments defined after the constant value. More than one argument can be defined in the constructor, enum constructors can be overloaded, just like in normal class. Enum can implement one or more interfaces, but cannot extend other classes. Also other classes cannot extend enum, because all constructors in enum are assumed to be with private modifier. Enum cannot be defined with final modifier.

Constant specific class body comes in demand when you need a particular constant to override a method defined in enum. Below there is an example:

Leave a Reply

Your email address will not be published. Required fields are marked *