Polymorphism in Java

May 13, 2017

The literal meaning of Polymorphism is having different forms. This principle can be applied in Java or any other Object Oriented language.

Subclasses of a superclass can define their unique behaviors and yet share the same functionality of the parent class.

There are two forms of Polymorphism:

  • Method Overloading
  • Method Overriding

Method Overloading –

In a class when two methods are created with the same name but different arguments (different number or the different type of arguments).

Let us consider an example:

Let say we have a class called Shape: To calculate the area of different shapes. Consider three shapes – square, rectangle, and circle.

Area of Square: side * side;

Area of Rectangle: length * width;

Area of Circle: PI * radius * radius;

Here, I will create a class with name Shape. It will have three methods with the same name say calculateArea(). One for calculating the area of Square, only one argument of type int will be passed, for Rectangle – two arguments, both of type int will be passed and another method to calculate the area of circle – one argument of type double is passed.

See below code for better understanding:

Method Overriding –

When methods with same name and same signature are implemented in both superclass and subclass is known as Method Overriding. Here, the implementation written in subclass overrides the implementation of the super class.

Sometimes, there is a requirement that you can use some of the existing methods of a class, but a few requires some changes. You can override all those methods which require changes.

Let us consider an example: we have a class Machine with a run method with some implementation, and we want different implementation in Car class which extends this Machine class.

When this code is executed, for both run calls – “Car is running” will be printed.

This also states that Method overriding is a runtime polymorphism because it is decided at runtime which method to execute.

Some points to remember for Method Overriding:

  • Methods must have the same name.
  • Methods must have same arguments.
  • Static Methods cannot be overridden because static methods belong to class not to object.
  • We cannot override the main method because it is a static method.
  • If you override a method, overridden method must not be more restricted. Example – a protected method cannot be overridden by a default method.

PS: For any questions, queries or comments feel free to write us at support@qatechub.com or saurabh@qatechhub.com


About the Author


Follow Saurabh:

Leave a Comment: