ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
interface Greeter {
default String hello() { return "Hi"; }
}
class Formal implements Greeter {
@Override
public String hello() { return Greeter.super.hello() + ", good day"; }
}
// in main:
Greeter g = new Formal();
System.out.println(g.hello());- A. Hi
- B. Hi, good day
- C. Compile-time error: an interface's default method cannot be called via super from a class
- D. Compile-time error: Greeter.super is only valid inside another interface
Correct answer: B. Hi, good day
InterfaceName.super.method() is valid syntax inside an implementing class whenever it needs to explicitly invoke that interface's default implementation. Formal.hello() calls Greeter's default ("Hi") and appends ", good day", so g.hello() (dispatched dynamically to Formal's override) returns "Hi, good day".
More OOP with C++ and Java questions
- What is printed? cpp struct Base { Base() { cout << "Base-ctor "; } ~Base() { cout << "Base-dtor "; } }; struct Derived : Base { Derived()…
- What is printed? java public class Main { static int risky() { try { return 1; } finally { return 2; } } public static void main(String[]…
- What is printed? java class MyChecked extends Exception { MyChecked(String m) { super(m); } } public class Main { static void risky()…
- Which statement about this code is correct? java class Main { static void risky() { if (Math.random() < 2) throw new…
- What is printed? java public class Main { public static void main(String[] args) { int result = compute(); System.out.println(result); }…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try {…