Lesson 17 of 20

Enums

Enums

An enum (short for enumeration) is a special class that represents a fixed set of constants. Use enums when a variable can only take one of a small set of possible values.

Basic Enum Declaration

enum Direction {
    NORTH, SOUTH, EAST, WEST
}

Direction d = Direction.NORTH;
System.out.println(d);           // NORTH
System.out.println(d.name());    // NORTH
System.out.println(d.ordinal()); // 0

Enum Methods

Every enum gets useful methods automatically:

  • name() — returns the constant name as a string
  • ordinal() — returns the position (0-based)
  • values() — returns an array of all constants
  • valueOf(String) — converts a string to the enum constant

Enums with Fields and Constructors

Enums can have fields, constructors, and methods:

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

    private final double mass;
    private final double radius;

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

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

Enums with Abstract Methods

Each constant can override an abstract method:

enum Operation {
    ADD { double apply(double a, double b) { return a + b; } },
    SUB { double apply(double a, double b) { return a - b; } };

    abstract double apply(double a, double b);
}

Your Task

  1. Create an enum Season with constants SPRING, SUMMER, AUTUMN, WINTER, each having a label field (e.g. "Warm", "Hot", "Cool", "Cold") and a getLabel() method.

  2. Create an enum MathOp with constants ADD, SUB, MUL, each overriding an abstract method int apply(int a, int b).

  3. In main, iterate over all seasons printing name: label, then use each MathOp on 10 and 3.

TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.