Java ProgramsOOPEnum Class

Enum Class in Java

beginner·  OOP  ·  Enums

Problem

An enum is a type whose values are a fixed, known set of constants — unlike a plain class, you can never create an instance of it beyond the ones the enum itself declares.

Define a Season enum where each constant carries its own weather description, then list every season and branch on one specific value.

Input
Season.values(), then switch on Season.SUMMER
Output
WINTER: Cold SUMMER: Hot MONSOON: Rainy Wear light clothing

Java Program

Java
enum Season { WINTER("Cold"), SUMMER("Hot"), MONSOON("Rainy"); private final String weather; Season(String weather) { // runs once per constant, at class-loading time this.weather = weather; } String getWeather() { return weather; } } public class EnumClassDemo { public static void main(String[] args) { for (Season season : Season.values()) { System.out.println(season + ": " + season.getWeather()); } Season current = Season.SUMMER; switch (current) { case SUMMER: System.out.println("Wear light clothing"); break; default: System.out.println("Dress accordingly"); } } }

Output

WINTER: Cold SUMMER: Hot MONSOON: Rainy Wear light clothing

Core Logic

Giving each enum constant its own constructor argument attaches real data to what would otherwise be a bare named constant, and values() hands back every constant for free.

How It Works
  1. 1enum Season { WINTER("Cold"), SUMMER("Hot"), MONSOON("Rainy"); } declares exactly three constants, each passing its own argument to the enum's constructor.
  2. 2The constructor Season(String weather) runs once per constant, at class-loading time, storing that constant's argument in its own weather field.
  3. 3Season.values() returns every declared constant, in declaration order, letting the loop print each one's name and weather together.
  4. 4The switch (current) statement branches directly on which constant current holds, the same way it would switch on an int or a String.
The loop prints all three seasons and their weather; then, with current = Season.SUMMER, the switch matches the SUMMER case and prints "Wear light clothing".
💡

Key Point: Each constant runs the constructor with its own arguments exactly once — WINTER, SUMMER, and MONSOON each end up with a different weather value baked in, permanently, from the moment the enum is loaded.

Key Concepts

enumenum constructorvalues()switch on enum

Related Programs