Polymorphism in Java

Ratings:
(4)
Views: 0
Banner-Img
Share this blog:

Polymorphism in Java

Polymorphism is one of the major building blocks of object oriented programming along with inheritance, abstraction and encapsulation. Polymorphism is an Oops concept which advice use of 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 arise in near future due to new implementation of our common interface. If we don't use 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 other object oriented language like C++ also supports polymorphism and it comes as fundamental along with other OOPS concepts like Encapsulation , Abstraction and Inheritance. An example of polymorphism is referring the instance of subclass, with reference variable of super-class. e.g.

Object o = new Object(); //o can hold the reference of any subtype
Object o = new String();
Object o = new Integer();

What is meant by run time polymorphism in Java?

Dynamic (run time) polymorphism is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.

What is meant by compile time polymorphism?

It is also known as Static binding, Early binding and overloading as well. It is also known as Dynamic binding, Late binding and overriding as well. Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature and different return type.

What is runtime polymorphism or dynamic method dispatch in Java?

Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to.

Is overloading a form of polymorphism?

The keyword in here is overriding, overloading is different and is not considered as polymorphism. with overloading you can define multiple methods "with same name" but with different parameters on same object or class. java doesn't truly offer this level of polymorphism (called also object slicing).
 
In java language, polymorphism is essentially considered into two versions.
  • Compile time polymorphism (static binding or method overloading)
  • Runtime polymorphism (dynamic binding or method overriding)

Compile time polymorphism

The process of binding the overloaded method within object at compile time is known as Static polymorphism due to static polymorphism utilization of resources (main memory space) is poor because for each and every overloaded method a memory space is created at compile time when it binds with an object. In C++ environment the above problem can be solve by using dynamic polymorphism by implementing with virtual and pure virtual function so most of the C++ developer in real worlds follows only dynamic polymorphism.

Dynamic polymorphism

In dynamic polymorphism method of the program binds with an object at runtime the advantage of dynamic polymorphism is allocating the memory space for the method (either for overloaded method or for override method) at run time.

Example of Dynamic polymorphism.

In below example we create two class Person an Employee, Employee class extends Person class feature and override walk() method. We are calling the walk() method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Here method invocation is determined by the JVM not compiler, So it is known as runtime polymorphism.

class Person
{
void walk()
{
System.out.println("Can Run....");
}
}
class Employee extends Person
{
void walk()
{
System.out.println("Running Fast...");
}
public static void main(String arg[])
{
Person p=new Employee(); //upcasting
p.walk();
}
}
Output
Running fast...

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 method based on a particular object at run-time instead of declared type while coding. To get hold of 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";
   }
}

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: 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. Variable names: Always use Super type while you are storing reference 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 reference from Factory:

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

Return type of method The return type of any method is another place where you should be using 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
  }

For indepth understanding of Java click on

Java Tutorials

Java Virtual Machine

Multi threading in java

Exception Handling in Java

Interface in Java

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox