Accessing the java Object class methods using an interface reference

我们两清 提交于 2019-12-21 19:41:09

问题


Let's consider the following example.

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() {}

}

I thought, in Java using interface reference we may access only methods that are defined in this interface. But, it seems that it is allowed to access method of class Object via any interface reference. My concrete class "SimpleClass" inherits all the methods that class Object has and definitely the class Object doesn't implement any interface (one would assume that Object implements some interface with methods like notify, wait and etc.). My question is, why it is allowed to access methods of the class Object via interface reference, taking into consideration that other methods in my concrete class are not allowed?


回答1:


why it is allowed to access methods of the class Object via interface reference

You can invoke the Object class methods using an interface reference although an interface doesn't extend from Object class, because every root interface in Java has implicit declaration of method corresponding to each method of Object class.

JLS §9.2 - Interface members:

The members of an interface are:

  • If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.



回答2:


This is because Java ensure that any class which has implemented the X interface is definitely is a Object class too, so this is possible to call the wait(), notify() and other Object guys.



来源:https://stackoverflow.com/questions/19469333/accessing-the-java-object-class-methods-using-an-interface-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!