在 Java 8 中创建默认方法时,某些 Object
方法无法从默认方法中调用。例如:
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.
}
}
似乎 clone()
和 finalize()
是 Object
中唯一不允许的方法。巧合的是,这些是 Object
中唯一 protected 方法,但这个问题特别针对默认方法,因为它们将由扩展 java.lang.Object< 的类继承
。这是什么原因?
最佳答案
Object
中的 protected
方法在接口(interface)的 default
方法中不可用并非巧合。
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.
接口(interface)不会从 Object
继承任何东西,但它会隐式声明所有 public
Object
方法。这不包括任何 protected
方法。这就解释了为什么不能调用clone
和finalize
;它们未在接口(interface)中声明。
关于java - 为什么某些对象方法不能从默认方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36894508/