Polymorphism in Java – OOPS Concepts

This post talks about one of the OOPS concept polymorphism and the usage of polymorphism in Java.

What is polymorphism

Polymorphism is one of the four fundamental principles of Object Oriented Programming along with inheritance, abstraction and encapsulation.

Polymorphism is a Greek word where poly means “many” and morph means “change from one form to another”. In object oriented terms it relates to the same object reference taking many forms.

The concept of polymorphism in Java is designed as an interface having a method and the derived classes implementing the interface as per their requirement. Then using the reference of that single interface any of those implemented class methods can be invoked. So one interface reference can take many forms here based on which class it is referring to.

Polymorphism in Java

There are two types of polymorphism in Java-

  1. Compile time polymorphism– Also known as static polymorphism. Static polymorphism in Java is achieved through Method overloading as it is known at compile time itself which of the overloaded method will be called.
  2. Runtime polymorphism– Also known as dynamic polymorphism. Dynamic polymorphism in Java is achieved through Method overriding. In method overriding it is resolved at run time which of the overridden method would be called.

Example of Run time polymorphism in Java

In the example there is an interface Payment with a method doPayment(double amount). This interface is implemented by two classes.

Implementing class -1

Implementing class -2

Output

As you can see at run time reference of Payment can refer to any of these implementations and based on the current reference that class’ method is called.
Polymorphism in Java

Example of Compile time polymorphism in Java

Here in the class there are two methods with the same name (add) but the types of parameters are different so these are overloaded methods. Based on the types of arguments passed in the method call appropriate add method is called. This binding is done at the compile time itself.
Output

That’s all for the topic Polymorphism in Java – OOPS Concepts. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.