Enums: constants, fields, constructors & switch

Enums are full classes — add fields, methods, and interface implementations.

Enums are not just named integers

An enum is a special class whose instances are a fixed, named set. The basic form:

public enum Season { SPRING, SUMMER, AUTUMN, WINTER }

Season s = Season.SUMMER;
System.out.println(s.name());       // SUMMER
System.out.println(s.ordinal());    // 1  (zero-based)

Season[] all = Season.values();     // all constants in declaration order
Season w = Season.valueOf("WINTER"); // by name — throws IllegalArgumentException if unknown

Enums in switch

switch (s) {
    case SPRING -> System.out.println("plant");
    case SUMMER -> System.out.println("grow");
    default     -> System.out.println("rest");
}

Enums with fields and methods

An enum can have instance fields, a private constructor, and methods. The constants become objects constructed with those arguments:

public enum Planet {
    MERCURY(3.303e+23, 2.4397e6),
    EARTH  (5.976e+24, 6.37814e6);

    private final double mass;    // kg
    private final double radius;  // m

    Planet(double mass, double radius) {   // private — always
        this.mass   = mass;
        this.radius = radius;
    }

    double surfaceGravity() {
        final double G = 6.67300E-11;
        return G * mass / (radius * radius);
    }
}

Enums implementing interfaces

An enum can implement any interface; each constant can even override the method individually (via an anonymous class body per constant). Enums cannot extend a class (they already extend java.lang.Enum).

NORMAL ~/memra/learn/java-from-zero/enums utf-8 LF