ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
interface Greeter { String greet(); }
class Main {
    public static void main(String[] args) {
        Greeter g = () -> "hi from lambda";
        Greeter g2 = new Greeter() {
            public String greet() { return "hi from anon class"; }
        };
        System.out.println(g.greet() + " | " + g2.greet());
    }
}
  1. A. hi from lambda | hi from anon class
  2. B. Compilation error: Greeter is not a functional interface
  3. C. hi from anon class | hi from lambda
  4. D. null | null

Correct answer: A. hi from lambda | hi from anon class

Greeter has exactly one abstract method, so it is a valid functional interface usable with a lambda; both the lambda and the anonymous class supply their own greet() implementation, dispatched (conceptually, polymorphically) to produce their respective strings.

More OOP with C++ and Java questions

Exams that ask this topic