Know everything about polymorphism in JAVA

Archit Pandita
3 min readJan 3, 2021

--

Polymorphism is one of the important term in object oriented programming languages like C++,JAVA etc.

Poly means “many” and morph means “forms” in Greek.Hence,we can define polymorphism as the ability of a message to be displayed in more than one form.

Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. This is called polymorphism.

There are two types of polymorphism in Java.

  1. Compile time or Static Polymorphism.
  2. Runtime or Dynamic Polymorphism.

Compile-time polymorphism: It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. But Java doesn’t support the Operator Overloading.But C++ supports Operator Overloading.

So we will consider only method overloading and understand with the example.

Method Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or change in type of arguments or both.

Important Note :

What if two methods have same signature and different return types?

If two methods have same signature and different return types, then those methods will not be treated as two different methods or methods overloaded. For duplication, compiler checks only method signature not return types. If method signature is same, straight away it gives duplicate method error.

For detailed method overloading concept refer this.

2. Runtime polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.

Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

Java Runtime Polymorphism with Data Member

A method is overridden, not the data members, so runtime polymorphism can’t be achieved by data members.

In the example given below, both the classes have a data member speedlimit. We are accessing the data member by the reference variable of Parent class which refers to the subclass object. Since we are accessing the data member which is not overridden, hence it will access the data member of the Parent class always.

Rule: Runtime polymorphism can’t be achieved by data members.

--

--