• Polymorphism which refers to the idea of having many forms occurs when there is hierarchy of classes related to each other through inheritance.
  • A call to a member method will cause a different implementation to be exected , depending on the type of the object invoking the method.
  • e.g Dog and Cat are the classes that inherit from the Animal class.Each class has its own implementation of makesound() method.
class Animal{ 
      public void makesound(){ 
} } 
class cat extends Animal{ 
      public void makesound(){ 
} } 
class Dog extends Animal{ 
       public void makesound(){ 
} } 
class Program{ 
          public static void main(String args[]){ 
                 Animal a = new Dog(); 
                 Animal b = new Cat(); 
} }
  • We have created two reference variable of type Animal & pointed them to Cat & Dog Object.
  • Animal a = new Dog() ;      Animal b = new Cat() ;
  • As the reference variable a contain a Dog Object , the makesound() method of the Dog class will be called.   ( a.makesound();  ).
  • Types of Polymorphism:- Overloading             Overriding