Compile-time polymorphism vs Run-time polymorphism



This is a very important interview question. Simply Compile-time polymorphism is known as overriding and Run-time polymorphism is known as overloading. I think you may know about the differences between both overloading and overriding. (OOP concepts)


But the question is, If someone asked why it is called compile-time polymorphism and run-time polymorphism? Let's try to find out the answers by examples.

Overriding is called run-time polymorphism. WHY ???


Look at the following example.



In this example, I've created a parent class, a child class, and the main class. Then I have created a Child object by Parent reference. 

Compile-time
  • In compile time it takes care of the Parent reference. Because objects are created in the run time
  • First, it checks is there any eat() method in the Parent class. 
  • In this example Parent class has eat() method. 
  • So it doesn't give any exception in the compile-time and the compilation will be a success.
Run time
  • AT the run time it takes care of the Child reference and it creates the new child object.
  • Then it checks is there any eat() method in Child class. 
  • There is an eat() method in Child also. Then this method will be called at the run time. 
  • It means object creation is happening at the run time by JVM and Run time is responsible to call which eat() method to call.
  • That is why it is called run-time polymorphism (Dynamic polymorphism)

Overloading is called compile-time polymorphism. WHY ???

Look at the following example.




In this case, a single class has the same methods with two different parameters. As you know it is called method overloading. 

Compile-time
  • In compile time it checks animal.eat() method in Animal class. 
  • No arg eat() method is there in the animal class.
  • According to the parameter list, it will call which method should be called.
  • Then the compilation is OK.

Run time
  • At the run time it creates the same Animal type object.
  • Then it checks the same thing that it did at the compile time.
  • It means compile time is enough to check which method should be called.
  • That is why it is called Compile time polymorphism ( Static polymorphism).


Finally

Overriding    = run-time polymorphism         = dynamic polymorphism
Overloading  = compile-time polymorphism  = static polymorphism





Compile-time polymorphism vs Run-time polymorphism Compile-time polymorphism  vs Run-time polymorphism Reviewed by Ravi Yasas on 12:56 PM Rating: 5

1 comment:

Powered by Blogger.