๐ŸŽ™ Free live masterclass ยท Sun, 29 Nov, 7:00 pm IST ยท Java Full Stack roadmap Register free โ†’
Skills101

AdvancedOOP Concepts ยท Lesson 18 of 18 ยท Updated ยท

Enums in Java Are Objects โ€” Fields, Constructors, Methods and Constant-Specific Behaviour

Many programs need a fixed set of values: days of the week, ticket classes, order status (PLACED, SHIPPED, DELIVERED), exam grades. Java's enum (short for enumeration) is made for this. In many languages an enum is just a set of named numbers. In Java it is much more: an enum is a class, and each constant is an object of that class. That makes enums a neat example of OOP ideas โ€” encapsulation, polymorphism and controlled object creation โ€” all in one feature.

1. The problem with int constants

Before enums, programmers used integer constants:

public class Main {
    static final int TEA = 1;
    static final int COFFEE = 2;

    static int price(int drink) {
        return drink == TEA ? 10 : 20;
    }

    public static void main(String[] args) {
        System.out.println(price(TEA));
        System.out.println(price(42));     // no such drink, but it compiles and runs
    }
}
10
20

price(42) happily returns a price for a drink that does not exist. The compiler cannot help, because the parameter is just an int. An enum type fixes this: a method that takes a Drink can only receive one of the declared Drink constants (or null).

2. A basic enum and its built-in methods

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

public class Main {
    public static void main(String[] args) {
        Day d = Day.valueOf("SAT");                 // String -> constant
        System.out.println(d + " " + d.ordinal() + " " + d.name());
        System.out.println(Day.values().length + " days");
        switch (d) {
            case SAT, SUN -> System.out.println("weekend");
            default -> System.out.println("weekday");
        }
        System.out.println(d == Day.SAT);
    }
}
SAT 5 SAT
7 days
weekend
true
MethodWhat it gives
values()An array of all constants, in declaration order
ordinal()The position, starting at 0 (SAT is 5)
name() / toString()The constant's name as written
valueOf("SAT")The constant with that name; throws IllegalArgumentException for an unknown name

Because each constant exists exactly once, comparing with == is safe and correct for enums. This is not true for normal objects such as strings.

3. Enums with fields, a constructor and methods

Since an enum is a class, it can have fields, a constructor and methods. Each constant passes its own values to the constructor. Here, each grade knows its minimum marks and a remark, and a static method finds the grade for any marks:

enum Grade {
    A(90, "Excellent"), B(75, "Very good"), C(60, "Good"), D(40, "Pass"), F(0, "Fail");

    private final int minMarks;
    private final String remark;

    Grade(int minMarks, String remark) {         // implicitly private
        this.minMarks = minMarks;
        this.remark = remark;
    }

    String remark() { return remark; }

    static Grade of(int marks) {
        for (Grade g : values()) {
            if (marks >= g.minMarks) return g;   // values() is A, B, C, D, F
        }
        throw new IllegalArgumentException("marks: " + marks);
    }
}

public class Main {
    public static void main(String[] args) {
        int[] marks = {95, 78, 61, 40, 12};
        for (int m : marks) {
            Grade g = Grade.of(m);
            System.out.println(m + " -> " + g + " (" + g.remark() + ")");
        }
    }
}
95 -> A (Excellent)
78 -> B (Very good)
61 -> C (Good)
40 -> D (Pass)
12 -> F (Fail)

The Grade enum has exactly five objects, A to F, each holding its own minMarks and remark; the private constructor stops anyone creating more

Notice the OOP ideas at work:

  • Encapsulation: the grading rules live inside Grade, not scattered across if statements in the program. Changing the pass mark means changing one number.
  • Controlled creation: an enum constructor is always private. Nobody can write new Grade(...), so there are exactly five Grade objects โ€” ever.
  • Immutability: the fields are final, which is the normal and recommended style for enums.

A 0 to 100 number line split into bands F, D, C, B, A at 40, 60, 75 and 90, with 95, 78, 61, 40 and 12 mapped to A, B, C, D and F

4. Constant-specific behaviour: one abstract method, many versions

An enum can declare an abstract method, and each constant then provides its own body. This is runtime polymorphism inside one type โ€” and a compact form of the Strategy pattern.

enum Operation {
    PLUS("+")   { int apply(int a, int b) { return a + b; } },
    MINUS("-")  { int apply(int a, int b) { return a - b; } },
    TIMES("*")  { int apply(int a, int b) { return a * b; } },
    DIVIDE("/") { int apply(int a, int b) { return a / b; } };

    final String symbol;
    Operation(String symbol) { this.symbol = symbol; }

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

public class Main {
    public static void main(String[] args) {
        for (Operation op : Operation.values()) {
            System.out.println("12 " + op.symbol + " 4 = " + op.apply(12, 4));
        }
    }
}
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3

If you add a new constant, say MOD, and forget to write its apply, the code does not compile. With a switch spread across the program, a forgotten case is easy to miss.

Some more facts interviewers ask:

  • Every enum automatically extends java.lang.Enum, so an enum cannot extend another class. It can implement interfaces.
  • Enum constants are created once, when the enum class is first used.
  • A single-constant enum (enum AppConfig { INSTANCE; }) is a widely recommended way to write a Singleton, because Java itself guarantees only one instance, even with serialization.

5. EnumMap and EnumSet

The library has collections built specially for enum keys. EnumMap is a map whose keys are enum constants; EnumSet is a set of constants. Internally they use the ordinal as an array index (or bit position), so they are compact and fast, and they keep declaration order.

import java.util.*;

enum Status { PRESENT, ABSENT, LEAVE }

public class Main {
    public static void main(String[] args) {
        Status[] week = {Status.PRESENT, Status.PRESENT, Status.ABSENT,
                         Status.PRESENT, Status.LEAVE, Status.PRESENT};
        EnumMap<Status, Integer> count = new EnumMap<>(Status.class);
        for (Status s : week) count.merge(s, 1, Integer::sum);
        System.out.println(count);

        EnumSet<Status> notPresent = EnumSet.complementOf(EnumSet.of(Status.PRESENT));
        System.out.println(notPresent);
    }
}
{PRESENT=4, ABSENT=1, LEAVE=1}
[ABSENT, LEAVE]

Common mistakes

  • Storing ordinal() in a database or file. If someone inserts a new constant in the middle, every stored number now means something else. Store name() instead.
  • Calling valueOf with user input without handling IllegalArgumentException (wrong spelling or case: "sat" is not "SAT").
  • Writing if (grade.equals(Grade.A)) and worrying it is wrong โ€” it works, but == is the usual, null-safe way for enums.
  • Trying enum Grade extends Something. Enums already extend Enum; use implements with an interface.
  • Making enum fields non-final and changing them at runtime. Every part of the program shares the same constant objects, so a change affects everyone.

Quick recap

  • An enum is a class; each constant is its one and only object.
  • Built-ins: values(), ordinal(), name(), valueOf(); compare constants with ==.
  • Enums can have final fields, a (private) constructor and methods.
  • An abstract method lets each constant have its own behaviour โ€” polymorphism without switch.
  • Enums cannot extend classes but can implement interfaces; EnumMap and EnumSet are the fast collections for them.

Practice what you learned

๐Ÿ“ Quiz: Java Enums5 questions ยท instant answers & explanations ยท +10 XP ยท counts towards your free certificateTake the quiz โ†’