Master java skills

Run Time Polymorphism vs Compile Time polymorphism

We know what polymorphism is. Many forms by the same object. Real world example can be a woman. She has many forms. At home, she is a mother, sister, wife, at office she is an employee etc.

In java, polymorphism is two types: Compile Time Polymorphism and Run Time Polymorphism.

  1. Compile time polymorphism is achieved by method overloading. It is known as compile time or static polymorphism because call resolution of overloaded methods is done at the compile time itself. Parameters decide which overloaded version of a method will be called.
  2. Run time polymorphism, at the other hand, is also known as dynamic polymorphism. Because call resolution of methods does not happen at compile time. Rather it happens at run time when actual object are created. It is achieved by method overriding. The type of object decide which overridden method would be called at runtime.

Compile Time Polymorphism

From the above diagram, it is clear that which method is called is decided by the parameters in the method call. Compiler itself can decide which overloaded method is called. This is why it is called Compile Time Polymorphism.

To understand more about compile time polymorphism with java examples, click here.

Run Time Polymorphism

Method overriding is the way to achieve run time polymorphism in java. In method overriding, method call resolution doesn’t happen at compile time, rather it happens at run time. Which overridden method will be called depends upon on which object it is called. Since the object creation happen at run time, call resolution also happen at run time.

Method overriding is also called dynamic polymorphism or dynamic method dispatch.

To understand more about run time polymorphism with java examples, click here.