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; }
}- A. It compiles and every Named object compares equal to any other Named
- B. It compiles but the default is ignored at run time
- C. Compile-time error: a default method cannot override a method of Object
- 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
- Which of these is a valid functional interface (usable as a lambda target)?
- What is printed? java class T { String name = "outer"; void run() { Runnable a = () -> System.out.print(this.name + " "); Runnable b = new…
- What is printed? java // Java 16 or later record P(int x, int y) { } // in main: P a = new P(1, 2), b = new P(1, 2); System.out.print((a…
- What happens when this is compiled? java class P { P(int x) { } P() { } } class C extends P { } // in main: C c = new C(5);
- What happens when C is compiled? java class P { static void s() { } } class C extends P { @Override static void s() { } }
- Which lazily-initialised singleton is thread-safe WITHOUT any explicit synchronization or volatile field?