nerdexam
Oracle

1Z0-809 · Question #237

Given: interface Interface1 { public default void sayHi() { System.out.println("Hi Interface-1"); } } interface Interface2 { public default void sayHi() { System.out.println("Hi Interface-2"); } }…

The correct answer is D. Hi MyClass. D is correct because MyClass explicitly overrides sayHi(), and Java's method resolution always prioritizes the concrete class implementation over any interface default methods. When obj.sayHi() is called, Java looks at the actual runtime type of the object (MyClass), not the…

Question

Given: interface Interface1 { public default void sayHi() { System.out.println("Hi Interface-1"); } } interface Interface2 { public default void sayHi() { System.out.println("Hi Interface-2"); } } public class MyClass implements Interface1, Interface2 { public static void main(String[] args) { Interface1 obj = new MyClass(); obj.sayHi(); } public void sayHi() { System.out.println("Hi MyClass"); } } What is the result?

Options

  • AHi Interface-2
  • BA compilation error occurs.
  • CHi Interface-1
  • DHi MyClass

How the community answered

(21 responses)
  • A
    5% (1)
  • B
    10% (2)
  • C
    5% (1)
  • D
    81% (17)

Explanation

D is correct because MyClass explicitly overrides sayHi(), and Java's method resolution always prioritizes the concrete class implementation over any interface default methods. When obj.sayHi() is called, Java looks at the actual runtime type of the object (MyClass), not the declared reference type (Interface1), so it finds and executes MyClass.sayHi().

A and C are wrong because interface default methods are only used when no class implementation exists - once MyClass provides its own sayHi(), both interface defaults are completely overridden and ignored, regardless of which interface the reference type is.

B is wrong because while implementing two interfaces with the same default method would cause a compile error if MyClass didn't override it (the "diamond problem"), the error is resolved exactly by providing the override - which MyClass does.

Memory tip: Think of the class as the "last word" - if the class defines a method, that's what runs, full stop. The reference type (Interface1 obj) only affects which methods are visible at compile time, not which implementation runs at runtime. This is the essence of Java polymorphism.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice