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());
}
}- A. hi from lambda | hi from anon class
- B. Compilation error: Greeter is not a functional interface
- C. hi from anon class | hi from lambda
- 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
- What is printed? cpp struct Resource { virtual ~Resource() { cout << "~Resource "; } }; struct FileResource : Resource { ~FileResource() {…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : virtual A { void f() override { cout << "B"; } }; struct C…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } public String toString() { return val + (next != null ?…
- What is printed? java class A { final String tag() { return "A"; } } class B extends A { String tag(int x) { return "B" + x; } } // in…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "1"; } }; struct D2…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "X"; } }; struct D2…