Friday, August 6, 2021

What is polymorphism in Java? Method overloading or overriding?

What is Polymorphism in Java
Polymorphism is an important Object oriented concept and is widely used in Java and other programming languages.  Polymorphism in java is supported along with other concepts like Abstraction, Encapsulation, and Inheritance. Few words on the historical side; Polymorphism word comes from ancient Greek where poly means much so polymorphic are something which can take many forms. In this Java Polymorphism tutorial, we will see what is Polymorphism in Java, How Polymorphism has been implemented in Java e.g method overloading and overriding, why should we use Polymorphism and how can we take advantage of it polymorphism while writing code in Java. Along the way, we will also see a real-world example of using Polymorphism in Java


polymorphism in java, java polymorphism example and tutorialBy the way, I learned about Abstraction, Encapsulation, and Polymorphism during my college time but was never able to recognize its real potential until I started doing programming and was involved in bigger projects. 

On theory, Polymorphism is a simple concept where one variable can denote multiple objects but in real life it is just a gem, and a code written using polymorphism concept is much flexible to change and quite easy to maintain than the one which is written without polymorphism. 

In Java programming whole concept of interface is based on Polymorphism and its a famous design principle that to code for interface than implementation to take advantage of Polymorphism and introducing new implementation in future.


What is polymorphism in Java?

Polymorphism is an Oops concept that advises the use of a common interface instead of concrete implementation while writing code. When we program for interface our code is capable of handling any new requirement or enhancement that arise in near future due to the new implementation of our common interface. 

If we don't use a common interface and rely on concrete implementation, we always need to change and duplicate most of our code to support new implementation. Its not only Java but another object-oriented language like C++ also supports polymorphism and it comes as fundamental along with other OOPS concepts like Encapsulation , Abstraction and Inheritance.



How Polymorphism supported in Java

Java has excellent support of polymorphism in terms of Inheritance, method overloading, and method overriding. Method overriding allows Java to invoke a method based on a particular object at run-time instead of declared type while coding. To get hold of the concept let's see an example of polymorphism in Java:

public class TradingSystem{
   public String getDescription(){
      return "electronic trading system";
   }
}

public class DirectMarketAccessSystem extends TradingSystem{
   public String getDescription(){
     return "direct market access system";
   }
}

public class CommodityTradingSystem extends TradingSystem{
   public String getDescription(){
     return "Futures trading system";
   }
}

Here we have a super class called TradingSystem and there two implementation DirectMarketAccessSystem and CommodityTradingSystem and here we will write code which is flexible enough to work with any future implementation of TradingSystem we can achieve this by using Polymorphism in Java which we will see in the further example.


Where to use Polymorphism in code

Probably this is the most important part of this Java Polymorphism tutorial and It’s good to know where you can use Polymorphism in Java while writing code. Its common practice to always replace concrete implementation with interface it’s not that easy and  comes with practice but here are some common places where I check for polymorphism:


1) Method argument:

Always use super type in method argument that will give you leverage to pass any implementation while invoking a method. For example:

public void showDescription(TradingSystem tradingSystem){
   tradingSystem.description();
}
If you have used concrete implementation e.g. CommodityTradingSystem or DMATradingSystem then that code will require frequent changes whenever you add new Trading system.



2) Variable names:

Always use Super type while you are storing references returned from any Factory method in Java, This gives you the flexibility to accommodate any new implementation from Factory. Here is an example of polymorphism while writing Java code which you can use retrieving references from Factory:

String systemName = Configuration.getSystemName();
TradingSystem system = TradingSystemFactory.getSystem(systemName);



3) The return type of method

The return type of any method is another place where you should be using the interface to take advantage of Polymorphism in Java. In fact, this is a requirement of Factory design pattern in Java to use interface as a return type for factory method.

public TradingSystem getSystem(String name){
   //code to return appropriate implementation
}


Method overloading and method overriding in Java

Method overloading and method overriding use concept of Polymorphism in Java where method name remains the same in two classes but an actual method called by JVM depends upon an object at run time and done by dynamic binding in Java

Java supports both overloading and overriding of methods. In case of overloading method signature changes while in case of overriding method signature remains same and binding and invocation of the method is decided on runtime based on actual object. 

This facility allows Java programmers to write very flexibly and maintainable code using interfaces without worrying about concrete implementation. One disadvantage of using Polymorphism in code is that while reading code you don't know the actual type which annoys you while you are looking to find bugs or trying to debug the program.

But if you do Java debugging in IDE you will definitely be able to see the actual object and the method call and the variable associated with it.


Parametric Polymorphism in Java

Java started to support parametric polymorphism with the introduction of Generic in JDK1.5. Collection classes in JDK 1.5 are written using Generic Type which allows Collections to hold any type of an object at run time without any change in code and this has been achieved by passing actual Type as a parameter. 

For example, see the below code of a parametric cache written using Generic which shows the use of parametric polymorphism in Java. Read how to create Generic class and methods in Java for more details.

interface cache{
  public void put(K key, V value);
  public V get(K key);
}



That’s all on polymorphism in java, for now, please suggest and share some of the other coding practices that involve the use of polymorphic behavior of java for the benefit of all. Thank you. 


Some more Interesting tutorials:

16 comments :

Anonymous said...

Polymorphism in Java is implemented in java with the use of interface, abstract class, method overloading and method overriding. you should also not forget that Inheritance also gives you ability to implement polymorphism by providing you substitution capability where a Base class can hold reference of derived class.

Ravi said...

what is the difference in method overloading and method overriding, does both comes under polymorphism ?

Prashant Neharkar said...

Both are the valid implementation of polymorphism concept.
Method Overloading demonstrates static polymorphism and Method Overriding is used in Dynamic Method Dispatch for implementation of Dynamic Polymorphism.

Javin @ stringbuffer vs Stringbuilder said...

Thanks Prashant,yes you are correct method overloading is a static polymorphism which resolves on compile time while method overriding resolved during run time.

Javin @ why main is declared static in java said...

Hi Joselyn you may like to check my post Difference between method overloading and overriding with example

SK said...

My understanding is method overloading is not a polymorphism and only method overriding is known as polymorphism

Sai Venkat said...

we have two types of polymorphisms one is static and another one is dynamic. Overloading is example for static polymorphism and Overriding is example for dynamic polymorphism

Anonymous said...

polymorphism is something where one message is ment in many ways

Anonymous said...

If I have a interface called HumanInterface and a class called Man that implements from HumanInterface whats the difference between
Man m = new Man();
and
HumanInterface m = new Man();

Unknown said...

wat is use of interface when we hav to give the implementation itself..

Prattek said...

What is difference between Polymorphism and overloading or Polymorphism to overrriding in Java ? Are Polymorphism and overriding are same thing ? Some people says there is difference between Overloading and Polymorphism and its not a true form of Polymorphism, What is your opinion ?

Gauri said...

Hello Javin, is method overloading is really example of polymorphism in Java? I have asked this question in an interview. I said yes because polymorphism means many forms and overlaoded method s has same name but different behaviors, but interviewer was not agreed. he says function overloading is not polymorphism because it's not based on type of object. Please help with this confusion

Anonymous said...

@Gauri -- You are right, method overloading is also a type of polymorphism. Polymorphism can be implemented by either static binding or late binding. Static binding is nothing but compile time polymorphism (achieved via method overloading) where the actual object is known during compile time.

MANOJ KUMAR said...

What is polymorphism?

Ability of an java object to take more than one form is polymorphism.

What does that mean?

Let's take an practical example to understand this

Say we have an living being called animal who is a horse .Now I can say

Horse is running
OR
Animal is running

both are correct .Thus single living being is taking two form here

1)Horse 2)Animal

Let's understand this by code

public class Animal{

}

public class Horse extends Animal{
}

Let us understand more on polymorphism here

Polymorphism Simplified

Anonymous said...

I am going to define-- What is polymorphism ? When an object shows different behavior at different class level is called polymorphism. Here behavior refers to the method. This can be achieved in two ways. First using method overloading i.e when we overload methods they must be differ either in argument length or argument type. Whenever we call the overloaded method, we specify which one method to be called based on the argument type we pass and no of argument we pass. So whichever method has to be called it is decided at compile time. Which is why this kind of binding(method declaration is binned with method body) is called early binding or static binding. Now come to method overriding. We know very well that method can be overridden in child class, and method implementation is according to the class specification different from base class. So when we want to call the the method using parent class reference variable the method will be called of the object which is being referred by the parent class variable. So this is decided when JVM allocates memory for the object in memory area. That's why the which method should be called is decided at run-time. So it is called run-time polymorphism and this kind of method binding is called late-binding or dynamic binding.

Anonymous said...

Polymorphism is a result of inheritance. It's all about overriding a method; it has absolutely nothing to do with overloading or interfaces! Polymorphism is also the most important and exciting thing about programming. It is also perhaps the single definition of the phrase "object oriented". If it ain't "polymorphic" it ain't "object oriented". Period!

Post a Comment