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:
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); }
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.