OOPs4Humans

Enums

A fixed set of constants.

Enums (Enumerations)

Analogy: state

An Enum is like a Traffic Light.

It can ONLY be RED, YELLOW, or GREEN.

It cannot be "PURPLE" or "BANANA". Enums restrict a variable to a specific set of allowed values.

The Traffic Light

Control the traffic light using an Enum.

  • RED: Stop!
  • YELLOW: Slow down.
  • GREEN: Go!

Traffic Light (Enums)

Set Enum State:

Current State: TrafficLight.RED

The Code

Use the enum keyword.

enum TrafficLight {
    RED,
    YELLOW,
    GREEN
}

TrafficLight currentLight = TrafficLight.RED;

if (currentLight == TrafficLight.RED) {
    System.out.println("STOP!");
}