让我们考虑下面的示例。使用接口引用访问java对象类方法
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实现了一些接口,例如notify,wait等方法)。我的问题是,为什么允许通过接口引用访问类Object的方法,考虑到我的具体类中的其他方法是不允许的?
谢谢。我认为这是可以接受的答案。所以,这意味着在Java中,任何接口都具有类Object的“隐藏声明”方法,对吗? – sergeyan
@sergeyan是的。究竟。 –