Reputation: 1183
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?
Upvotes: 4
Views: 7073
Reputation: 213261
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.
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.
Upvotes: 10
Reputation:
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.
Upvotes: 1