Compile Time vs Run Time Polymorphism

Polymorphism is one thing in many forms or the capacity to take on different forms.  When it applied to object-oriented programming languages like Java, it describes the ability of language to process objects of various types and classes through a single, uniform interface.

Polymorphism in Java is two types-

  1. Compile Time or Static Polymorphism

  2. Run Time of Dynamic Polymorphism

 

Compile Time or Static Polymorphism

Method overloading is a Compile time Polymorphism. It is also called static binding in Java. In this type, the method call is resolved by the the compiler (which method to be called). Static polymorphism can be achieved by overloading functions and overloading operators. The execution speed of compile time polymorphism is fast but it is less flexible because all things executed at compile time.

Let’s see the example of compile time polymorphism, here in below method, the methods call is resolved at compile time.

Output:

8
48
10.0

 

Tutorial on Automation Testing:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

 

Runtime or Dynamic Polymorphism

Method overriding is run time polymorphism. In run time, polymorphism call to the method is not resolved by the compiler. It’s also called dynamic method dispatch. As compare to compile time polymorphism it’s slow in execution but it is more flexible and things execute at run time.

Suppose we have the method with the same name in a parent class and in a child class, in that case, compiler doesn’t figure out which method to be call at compile time. So JVM decides the call to the method at runtime that’s why it is called Runtime polymorphism.

Output :

display() method of Child class
stub() method of Child class
Dummy() method of super class

 

In such case, JVM decides which display() method will be called at run time. Call to display() method can’t be resolved at runtime.

 

0 Comment

Leave a Reply