ProgrammingHardIBM · Deloitte pattern
What happens when this is compiled?
What happens when this is compiled?
interface A { default void m() { System.out.println("A"); } }
interface B { default void m() { System.out.println("B"); } }
class C implements A, B {
}- A. Compiles; C.m() picks A's default because A is listed first
- B. Compile-time error: C inherits two conflicting defaults for m() and must override it explicitly
- C. Compiles; calling c.m() is ambiguous and throws at runtime
- D. Compile-time error: a class cannot implement two interfaces with default methods
Correct answer: B. Compile-time error: C inherits two conflicting defaults for m() and must override it explicitly
When two interfaces supply unrelated default implementations of the same method, the implementing class is required to resolve the conflict by providing its own override; Java never silently prefers one default over the other, and this is a compile-time error, not a runtime one.
More OOP with C++ and Java questions
- What happens when Base b; is added inside main, right before the existing lines? cpp struct Base { virtual void f() = 0; }; struct Derived…
- What happens when this is compiled? cpp struct A { int x; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; d.x =…
- What is printed? cpp struct Base { virtual ~Base() {} }; struct Derived : Base {}; struct Other : Base {}; int main() { Base b = new…
- What is printed? java class Animal { void speak() { System.out.print(".."); } } class Dog extends Animal { void speak() {…
- What is printed? cpp struct Base { public: virtual ~Base() { cout << "~Base "; } }; struct Derived : Base { int data = new int[10]…
- What is printed? cpp struct Vehicle { virtual string type() { return "Vehicle"; } }; struct Car : Vehicle { string type() override {…