ProgrammingHardIBM · Deloitte pattern

What happens when this is compiled?

What happens when this is compiled?
enum Operation {
    ADD { public int apply(int a, int b) { return a + b; } },
    MULTIPLY { public int apply(int a, int b) { return a * b; } };
    public abstract int apply(int a, int b);
}
public class Main {
    public static void main(String[] args) {
        System.out.println(Operation.ADD.apply(2, 3) + " " + Operation.MULTIPLY.apply(2, 3));
    }
}
  1. A. Compile-time error: enum constants cannot have bodies
  2. B. 5 6
  3. C. Compile-time error: abstract methods are not allowed in enums
  4. D. 6 5

Correct answer: B. 5 6

Java enums may declare an abstract method and let each constant supply its own body (a constant-specific class body), effectively creating an anonymous subclass per constant. ADD.apply(2,3) runs its own body, 2+3=5; MULTIPLY.apply(2,3) runs its own, 2*3=6.

More OOP with C++ and Java questions

Exams that ask this topic