Skip to content
APPCITORThe Tech Blog
Esc

Java OOP – Polymorphism

August 10, 2020 2 min read

Java OOP – Polymorphism

Polymorphism is ability of a message to be displayed in more than one form. Simply, this allows us to perform single action in different ways. We can perform polymorphism in java by method overriding and method overloading. In last two articles we discussed about Inheritance (Part I and Part II). You can visit the article if you don’t know about inheritance, because inheritance is important to understand the concept Polymorphism.

Real world example for polymorphism – A man can be a father, a husband, a friend, an employee at the same time. This is polymorphism.

There are two types of polymorphism in java.

  1. Compile-time polymorphism
  2. Run-time polymorphism

Let’s discuss about the method overloading and method overriding first.

Method Overloading

Method overloading means having methods with same method name, but different parameters.

Method Overriding

Method overriding means having methods with the same name and same parameters. By overriding we can change the functionalities inherited by the super class to the sub class. That means overridden method should be in the sub class.

Let’s see an example using method overloading and method overriding.

Here you can see two methods with same name but different parameters in class A. That is method overloading.

Next you can see two methods with same name and same parameters in the class A and also class B. That is method overriding. Functions inside those two methods can be different as shown in the example.

Compile-time Polymorphism

This is also known as Static polymorphism. If you overload a static method in java, it is the example of compile-time polymorphism.

Run-time Polymorphism

This is also known as dynamic method dispatch. JVM is not running according to the bite code made by the compiler. If the method of sub class is different from the method of super class, then JVM decide what method should be run in the run-time. In method overriding, JVM decides to run the method of sub class. This happens only in run-time polymorphism. But in method overloading JVM decides to run the method of super class.

Java Example for run-time polymorphism:

Single interface and many forms

This is a benefit of run-time polymorphism. For the methods that JVM runs separately called single interface and many forms. To create a single interface we should create a super class and inherit. Also we should use polymorphism. We can do different functionalities by the same behavior. Let’s see an example.

Hope you guys got better knowledge on polymorphism. Next article will be on the topic “Java Packages”. Let’s discuss that topic before going to the next concept of OOP.

Thank you.

Share this article

Keep reading