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); }
}- A. 7 12
- B. 12 7
- C. Compilation error: Calculator has two implementations
- 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
- What is printed? java class Matrix { int[][] data; Matrix(int[][] d) { data = d; } Matrix add(Matrix other) { int[][] r = new…
- What is printed? java class Vehicle { private int speed; protected void setSpeed(int s) { speed = s; } int getSpeed() { return speed; } }…
- What is printed? cpp class Stack { vector<int> data; public: void push(int x) { data.pushback(x); } int pop() { int top = data.back()…
- What is printed? java interface Repository<T> { void save(T item); T find(int id); } class UserRepository implements Repository<String> {…
- What is printed? cpp class Printable { public: virtual void print() const = 0; virtual ~Printable() = default; }; class Report : public…
- What is printed? java class Shape implements Comparable<Shape> { double area; Shape(double a) { area = a; } public int compareTo(Shape o)…