-2
interface My
{
void show();
}

class Child implements My
{
   public void show()
    {
       System.out.println("hello from show");
    }
   public String toString()
    {
       System.out.println("Hello from toString");
       return "hello";
     }
   public static void main(String s[])
     {
        My m = new Child();
        m.show();
        m.toString();         
     }
  }

**In the above code m is the reference variable of My interface, and toString() method is of Object class, which has been overridden by Child class, but how come reference variable of My type can call the toString() method (prototype of toString is not present in My interfaces), if i'll try to call other personnel methods of Child class using m then it would give compilation error, but it is not happening in this case. Why so? **

2 Answers2

0

Every object in Java is descendent from Object. Therefore, Object's public methods are visible in all objects, including arrays, anonymous objects, and every other non-primitive object.

The other methods from Child are not visible because Java does not know that the reference is to the Child type. It knows for certain it's descendent from Object, because all objects are. This is a reference type? Then it is descendent from Object, whether it is through Child or any other class, it doesn't matter.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0

Since an interface can never be intantiated you'll always have a class implementing the interface. Since the class always extends Object you'll get the methods provided by Object in every interface (like equals, toString etc). Otherwise you would have to cast the interface to a known implementation which is not the idea behind it.

Ria
  • 1,900
  • 4
  • 14
  • 21