简体   繁体   中英

How it is possible to call methods of Object class on a 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.
   }
}

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, 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 an abstract 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.

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.

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

  • class type
  • interface type
  • array type
  • type variable ( T )
  • null type (for null )
  • intersection type ( A&B )

A subtype inherits methods from the supertype. Therefore all reference types inherit Object methods.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM