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?
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 methodm
with signatures
, return typer
, and throws clauset
corresponding to eachpublic
instance methodm
with signatures
, return typer
, and throws clauset
declared inObject
, unless anabstract
method with the same signature, same return type, and a compatiblethrows
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With