Reputation: 15416
interface TestInterface{
public void sayHello();
}
class A implements TestInterface{
public void sayHello(){
System.out.println("Hello");
}
public void sayBye(){
System.out.println("Hello");
}
public String toString(){
return "Hello";
}
public static void main(String args[]){
TestInterface ti=new A();
ti.sayHello();
ti.sayBye();//error
ti.toString();//How toString method can be called as it is not the part of the interface contract.
}
}
Upvotes: 4
Views: 173
Reputation: 19672
Every object is an Object
:) It would make sense to call Object
methods on objects.
That's the heart of the matter - all reference types are subtypes of Object
. Reference types include
T
)null
)A&B
)A subtype inherits methods from the supertype. Therefore all reference types inherit Object
methods.
Upvotes: 0
Reputation: 3576
This is the nature of OO Languages. Interfaces only define a set of method signatures that a concrete class needs to implements. They don't restrict the nature of the class (abstract v concrete).
So when you declare TestInterface ti
, in your example A
implements TestInterface
, so it is an instance of TestInterface
. Likewise class B implements TestInterface {...}
is also valid.
TestInterface ti = new A(); // Valid
ti = new B(); // Also valid (given the above definition)
Upvotes: -2
Reputation: 72844
From this section in the Java Language Specification:
If an interface has no direct superinterfaces, then the interface implicitly declares a
public abstract
member method m with signature s, return type r, andthrows
clause t corresponding to eachpublic
instance method m with signature s, return type r, andthrows
clause t declared inObject
, unless anabstract
method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.
So Object
's public methods like toString
are implicitly declared in all interfaces.
Upvotes: 4
Reputation: 393771
toString
can be called because any implementation of any interface must be a sub-class of Object, which contains the toString
method.
In order to call any other method that doesn't appear in the interface or in any super-interface your interface extends (and is not defined in Object
class), you must cast the interface to the type of the class that contains that method.
Upvotes: 1