ProgrammingVery hardProduct-company placement · Java

What happens when this interface is compiled?

What happens when this interface is compiled?
interface Named {
    String name();
    default boolean equals(Object o) { return o instanceof Named; }
}
  1. A. It compiles and every Named object compares equal to any other Named
  2. B. It compiles but the default is ignored at run time
  3. C. Compile-time error: a default method cannot override a method of Object
  4. D. Compile-time error: interfaces cannot declare equals

Correct answer: C. Compile-time error: a default method cannot override a method of Object

Java forbids default methods for equals, hashCode and toString, because the class's inherited Object method would always win anyway. Declaring them abstract in an interface is allowed.

More OOP with C++ and Java questions

Exams that ask this topic