Pankaj
Pankaj

Reputation: 15416

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.
   }
}

Upvotes: 4

Views: 173

Answers (4)

ZhongYu
ZhongYu

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

  • 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.

Upvotes: 0

Brett Walker
Brett Walker

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

M A
M A

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

Upvotes: 4

Eran
Eran

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

Related Questions