Are Interfaces "Object"?

Posted by PrashantGupta on Stack Overflow See other posts from Stack Overflow or by PrashantGupta
Published on 2012-07-09T02:30:33Z Indexed on 2012/07/09 3:16 UTC
Read the original article Hit count: 113

Filed under:
|
|
|
|
package inheritance;
class A{
   public String display(){
       return "This is A!";
   }
}

interface Workable{
   public String work();
}

class B extends A implements Workable{
   public String work(){
      return "B is working!";
   }
}

public class TestInterfaceObject{
   public static void main(String... args){
      B obj=new B();
      Workable w=obj;
      //System.out.println(w.work());
      //invoking work method on Workable type reference

      System.out.println(w.display());
      //invoking display method on Workable type reference

      //System.out.println(w.hashCode());
      // invoking Object's hashCode method on Workable type reference
    }
}

As we know that methods which can be invoked depend upon the type of the reference variable on which we are going to invoke. Here, in the code, work() method was invoked on "w" reference (which is Workable type) so method invoking will compile successfully. Then, display() method is invoked on "w" which yields a compilation error which says display method was not found, quite obvious as Workable doesn't know about it. Then we try to invoke the Object class's method i.e. hashCode() which yields a successful compilation and execution. How is it possible? Any logical explanation?

© Stack Overflow or respective owner

Related posts about java

Related posts about oop