Thursday 28 June 2012

How is it possible to access the equals method using a interface reference

How is it possible to access the equals method using a interface reference  

interface Shape {
   void draw();
}
class Square  implements Shape {
   int length,bredth;
   Square (int length,int bredth) {
      this.length = length;
      this.bredth = bredth;
   }
   @Override
   public void draw(){
      System.out.println("Inside Circle ");
   }
   public int getArea() {
      return length*bredth;  
   }
}

class ShapeMain {
   public static void main(String arg[]){
      Square obj = new Square(5, 5);
     
      System.out.println(obj.getArea()); // Calling getArea method from Square object is very well possible
      Shape s1 = obj;
      System.out.println(s1.getArea());
      //We know that  Calling getArea method from Shape reference will give a compile time
      //because getArea is not visible to Shape interface.
      Shape s2 = obj;
      System.out.println(s1.equals(s2));
      //Now the Crux is here .How is it possible to  call the equals method from the Shape interface which is         not declared ? See below for the answer
     
   }
}

By default All the public  methods in Object class will be declared in the interface  if such method is not already declared in the interface
Below is the snapshot from JLS Specification