ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
interface Calculator {
    int calculate(int a, int b);
}
public class Main {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;
        Calculator mul = (a, b) -> a * b;
        System.out.println(apply(add, 3, 4) + " " + apply(mul, 3, 4));
    }
    static int apply(Calculator c, int x, int y) { return c.calculate(x, y); }
}
  1. A. 7 12
  2. B. 12 7
  3. C. Compilation error: Calculator has two implementations
  4. D. 7 7

Correct answer: A. 7 12

Each lambda independently implements Calculator's single abstract method calculate(); apply() invokes it polymorphically through the interface reference, so add gives 3+4=7 and mul gives 3*4=12.

More OOP with C++ and Java questions

Exams that ask this topic