ProgrammingHardWipro · Cognizant pattern
What happens?
What happens?
interface A { default String id() { return "A"; } }
interface B { default String id() { return "B"; } }
class D implements A, B { }- A. It compiles, picking A's default because A is listed first
- B. Compilation error: D must override id() since neither default is more specific than the other
- C. It compiles, picking B's default because it is declared later
- D. It compiles and both defaults run, concatenated
Correct answer: B. Compilation error: D must override id() since neither default is more specific than the other
A and B are unrelated interfaces, so neither default method is more specific than the other (classic diamond with no common ancestor relation between them). Java refuses to guess and forces D to explicitly override id() itself (optionally delegating via A.super.id() or B.super.id()); the class fails to compile as written.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual void f() = 0; void greet() { cout << "greet "; f(); } }; struct Derived : Base { void f()…
- What happens? cpp struct Shape { virtual double area() const = 0; }; int main() { Shape s; cout << s.area(); }
- What is printed? java abstract class Vehicle { abstract void move(); void start() { System.out.print("starting "); move(); } } // in main…
- What is printed? cpp class Base { public: Base(int x) { cout << "Base(" << x << ") "; } }; class Derived : public Base { public: Derived()…
- What is printed? java class Outer { static class Nested { void show() { System.out.print("Nested.show"); } } } // in main: Outer.Nested n…
- What is printed? java interface Shape { double area(); static Shape unitSquare() { return () -> 1.0; } } // in main: Shape s =…