让我们考虑以下示例。
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() {}
}
我认为,在使用接口引用的 Java 中,我们只能访问在该接口中定义的方法。但是,似乎允许通过任何接口引用访问类 Object 的方法。我的具体类“SimpleClass”继承了 Object 类具有的所有方法,并且 Object 类肯定没有实现任何接口(人们会假设 Object 实现了一些带有通知、等待等方法的接口)。我的问题是,为什么允许通过接口引用访问类 Object 的方法,考虑到我的具体类中的其他方法是不允许的?