How can I call methods of class Object by reference of interface type?

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.
   }
}
+4
source share
4 answers

From this section in the Java Language Specification :

If the interface does not have direct superinterfaces, then the interface implicitly declares an element method public abstractm with signature s, return type r and sentence t21, corresponding to each instance method publicm with signature s, return type r and throws. t is declared inObject , if only a method abstractwith the same signature, the same return type and the offer of compatible throws is explicitly declared by the interface.

So, Objectpublic methods, such as toString, are implicitly declared in all interfaces.

+4

toString , Object, toString.

, , ( Object), .

+1

Object:). Object .

- Object.

  • type variable (T)
  • null type ( null)
  • (A&B)

. Object.

0

This is the nature of OO languages. Interfaces define only a set of method signatures that a particular class should implement. They do not limit the nature of the class (abstract v concrete).

So, when you declare TestInterface ti, in your example Aimplements TestInterface, therefore it is an instance TestInterface. Similarly class B implements TestInterface {...}.

TestInterface ti = new A(); // Valid
              ti = new B(); // Also valid (given the above definition)
-2
source

All Articles