使用接口引用访问java Object类方法

ser*_*yan 4 java inheritance interface

让我们考虑以下示例.

public interface SimpleInterface {
    public void simpleMethod();
}

public class SimpleClass implements SimpleInterface{

 public static void main(String[] args) {
     SimpleInterface iRef = new SimpleClass();
     SimpleClass cRef = new SimpleClass();
     iRef.simpleMethod(); // Allowed. Calling methods defined in interface via interface reference.
     cRef.specificMethod(); // Allowed. Calling class specific method via class reference.
     iRef.specificMethod(); // Not allowed. Calling class specific method via interface reference.
     iRef.notify(); // Allowed????

 }

 public void specificMethod(){}

 @Override
 public void simpleMethod() {}

}
Run Code Online (Sandbox Code Playgroud)

我想,在使用接口引用的Java中,我们可能只访问在此接口中定义的方法.但是,似乎允许通过任何接口引用访问类Object的方法.我的具体类"SimpleClass"继承了Object类所具有的所有方法,并且类Object确实没有实现任何接口(假设Object使用notify,wait等方法实现某些接口).我的问题是,为什么允许通过接口引用访问类Object的方法,同时考虑到我的具体类中的其他方法是不允许的?

Roh*_*ain 9

为什么允许Object通过接口引用访问类的方法

您可以Object使用接口引用调用类方法,尽管接口不会从Object类扩展,因为Java中的每个根接口都有对应于每个Object类方法的隐式方法声明.

JLS§9.2 - 接口成员:

接口的成员是:

  • 如果接口没有直接的超接口,则接口隐式声明一个公共抽象成员方法m,其中包含签名s,返回类型r和throws子句t,对应于具有签名s的每个公共实例方法m,返回类型r和throws子句t在Object中声明,除非接口显式声明具有相同签名,相同返回类型和兼容throws子句的方法.