Skip to content
Sharp

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
java
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);
}
Choose one answer
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.

Start free test
All Modern Java questions →