interface Intf {
}
class A implements Intf {
}
class Test {
public static void main(String[] args) {
Intf obj = new A();
obj.toString();
}
}
A friend had shown me this code, I could not explain it to him…
We know that methods defined in ‘referred’ object can only be run on an instance.
As we can see no method is defined by Intf but obj (which refers Intf) is able to call toString() method of Object.class
I consoled him saying that everything is an Object in Java (though we get no autofill option in eclipse IDE against Intf)
Actually, there is an implicitly declared
toStringmethod inIntf.Every interface (that doesn’t explicitly extend another interface) has an implicit method declaration for each public method in
Object.This is explained in detail in the Java Language Specification, § 9.2 Interface Members.