Raffi Khatchadourian Raffi Khatchadourian - 7 months ago 12
Java Question

Why are certain Object methods not callable from default methods?

When creating a default method in Java 8, certain

Object
methods are not callable from within the default method. For example:

interface I {
default void m() {
this.toString(); // works.
this.clone(); // compile-time error, "The method clone() is undefined for the type I"
this.finalize(); // same error as above.
}
}


It seems that
clone()
and
finalize()
are the only methods from
Object
that are not allowed. Coincidently, these are the only methods of
Object
that are protected, but this question is in particular regard to default methods, as they will be inherited by classes that do extend
java.lang.Object
. What is the reason for this?

Answer

It's not a coincidence that the protected methods from Object are not available in a default method in an interface.

Section 9.2 of the JLS states:

If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

An interface will not inherit anything from Object, but it will implicitly declare all public Object methods. This does not include any protected methods. This explains why clone and finalize can't be called; they are not declared in an interface.