ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
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);
}
// in main:
Operation op = Operation.valueOf("MULTIPLY");
System.out.println(op.apply(3, 4) + " " + op.ordinal() + " " + op.name());
  1. A. 12 1 MULTIPLY
  2. B. 7 1 MULTIPLY
  3. C. 12 0 MULTIPLY
  4. D. 7 0 ADD

Correct answer: A. 12 1 MULTIPLY

valueOf("MULTIPLY") resolves to the MULTIPLY constant, whose apply dispatches to its own override: 3*4=12. ordinal() returns its declaration-order position (MULTIPLY is the second constant, index 1). name() returns the exact declared constant name, "MULTIPLY".

More OOP with C++ and Java questions

Exams that ask this topic