Misconception About Polymorphism

Posted by
 As we all know what is Polymorphism?  Polymorphism is ability of method “to appear in many forms”.
Misconception- The web is full of the definitions “Compile time polymorphism” and “Run time Polymorphism”. There are two types of polymorphism one is “Compile Time Polymorphism” and second is “Run Time Polymorphism”.Example of Compile Time Polymorphism is “Method Overloading” and example of Run Time Polymorphism is “Method Overriding”.
Fact-  The above statements are complete misstatements. The only Polymorphism is the run time dispatch that some are misnaming “Run Time Polymorphism”. Overloading is never considered as polymorphism even oracle never described overloading as polymorphism check the following link:
Overloaded methods are just new methods to the compiler so it can not be polymorphism because definition of polymorphism itself says that “ability of behaving differently in different context is called polymorhism”. Second reason is the oracle’s statement about polymorphism “Subclasses of a class can define their own unique behaviours and yet share some of the same functionality”  It means Polymorphism is strictly related to Inheritance.
So the only polymorhism is overriding. You can understand polymorphism by following example.

 

Code:
 class Developer{  
      void choice()  
    {  
     System.out.println("I love all the languages!");   
    }  
 }  
 class JavaDeveloper extends Developer{  
   void choice()  
    {  
     System.out.println("I love Java!");   
    }  
 }  
 class DotNetDeveloper extends Developer{  
   void choice()  
    {  
     System.out.println("I love .Net!");   
    }  
 }  
 class PolymorphismDemo{  
   public static void main(String args[])  
   {  
     Developer d=new Developer();  
     Developer jd=new JavaDeveloper();  
     Developer dd=new DotNetDeveloper();  
     d.choice();  
     jd.choice();  
     dd.choice();  
   }  
 }  

 

Output:
 Misconception about Polymorphism
Explanation:All three variables are of Developer type and only one variable refers to instance of Developer and other two refers to instance of subclasses of developer. Method call depends on object type not on reference variable.”Which method will be called ” is identified at runtime depending on the object type. Overriding strictly follows polymorphism feature because the same method behaves differently based on the object type and also follows inheritance.

Leave a Reply