Search code examples
javainheritancecastingpolymorphismdynamic-binding

calling method in super class using object of sub class how it work?


class SuperClass{  
  public void print(){
    System.out.println("I'm super class...");
  }  
  public void someMethod(){
    System.out.println("any thing");
  }
}  

class SubClass extends SuperClass{ 
  @Override
  public void print(){
    System.out.println("I'm sub class...");
  }  

  public static void main(String args[]){  
    SuperClass a=new SubClass(); 
    a.print();  
    a.someMethod();
  }  
}  

a.print() known as dynamic binding and it's know which method to call in run time and choose method of SubClass because the object is SubClass it's true?

a.someMethod() how JVM deal with this method it's not in sub class and the object from sub class?


Solution

  • a.print() is an example of method overriding which is runtime polymorphism. That is, at runtime it decides whether to call the subclass method or the super class method (here your SubClass method is called as it is overridden and matches the parameter signature).

    In case of someMethod() call, you have not defined it in your SubClass. That means, your SubClass automatically got a someMethod() when you inherited it from Superclass as it is public. Putting it in simple words, SubClass also has the definition of someMethod(). Thats how JVM got to know which method to call.

    Also in SuperClass a, the variable 'a' will be stored in stack whereas the reference will be stored in heap. You have constructed the reference using SubClass's constructor. Meaning the variable 'a' in stack refers to a 'SubClass' object in heap. That is why 'a' is able to call someMethod