ProgrammingJava Senior Developer

How do enums work in Java, what nuances are associated with their use, and why is an enum not just a simple set of constants?

Pass interviews with Hintsage AI assistant

Answer

In Java, enum is a class type, a subclass of java.lang.Enum, representing a set of limited constant objects, but it is not limited to just a set of names: enums can be extended with methods, fields, constructors, implement interfaces, and add behavior.

Example:

enum Day { MONDAY("Weekday"), SATURDAY("Weekend"); private String description; Day(String description) { this.description = description; } public String getDescription() { return description; } } Day d = Day.SATURDAY; System.out.println(d.getDescription()); // "Weekend"

Nuances:

  • Enum guarantees the uniqueness of constants: instances are singletons.
  • Interfaces can be implemented.
  • Each value has its own class (methods can be overridden per-value).
  • Enum is protected from cloning and creating new instances through reflection.

Trick Question

Question: "Can methods be overridden in an enum for some enum values? If so — how?"

Common misunderstanding: it is mistakenly thought that all values always have the same behavior.

Correct answer: Yes, specific implementations for individual constants are possible.

Example:

enum Operation { PLUS { double apply(double x, double y) { return x + y; } }, MINUS { double apply(double x, double y) { return x - y; } }; abstract double apply(double x, double y); }

Examples of real errors due to ignorance of the nuances of the topic


Story

In a car owner accounting system, statuses were stored as enums, but they did not implement an additional field for the API code — developers tried to extend the enum through inheritance, which is forbidden. Eventually, they had to redo the status storage model.


Story

In an online store, programmers used a reflection utility to "unpack" the enum with a private constructor to create a fake instance for tests, but received an Exception: enums are protected from creating new instances. CI failed, tests crashed.


Story

In an old project, enum values were compared using equals() instead of ==. Unexpectedly, problems arose during deserialization: enum values are always compared using ==, since they are singletons.