Topic outline

    • Polymorphism is an object 's capacity to adopt multiple types. When a reference to the parent class is used to refer to a child class object, the most common use of polymorphism in OOP occurs. 


      It is considered that every Java object that can pass more than one IS-A test is polymorphic. In Java, all Java objects are polymorphic, as any object passes the IS-A test for its own type and object class.


      It is important to realise that a reference variable is the only possible way of accessing an entity. A variable relation may only be of one kind. Once declared, it is impossible to modify the form of a reference variable. 


      You may reassign the reference variable to other objects, provided that it is not declared final. The methods that can be invoked on the object will be defined by the form of the reference variable.


      Following is an example for the same- 


      class Animal {

       public void animalSound() {

         System.out.println("The animal makes a sound");

       }

      }

       

      class Pig extends Animal {

       public void animalSound() {

         System.out.println("The pig says: wee wee");

       }

      }

       

      class Dog extends Animal {

       public void animalSound() {

         System.out.println("The dog says: bow wow");

       }

      }