Modern Java · interview question
Given an enum with a method, how can each constant have a different implementation of that method?
Multiple choiceHardchapter-7-curatedpremiummodern-javaenums
enum Operation {
ADD { public int apply(int x, int y) { return x + y; } },
SUBTRACT { public int apply(int x, int y) { return x - y; } };
abstract int apply(int x, int y);
}Answer and explanation
Correct answer
B. Provide a method body for each constant
Why
Each constant in an enum can have its own implementation of a method by providing a method body directly within the constant declaration, similar to anonymous classes.
Test yourself on Modern Java
A free test with instant, explained results. No account needed.
More Modern Java questions
- What keyword is used to define a Java Record?
- Which pattern is effectively implemented when using enums to represent singletons?
- How can you iterate over all constants of an enum in Java?
- When designing a domain model, why should you be cautious about using records for classes with business logic?
- How can the use of enums improve the clarity of domain models in Java?
- When is a Java Record usually the better choice than a traditional class?