Saturday , February 23 2019
Home / Java / Polymorphism in java

Polymorphism in java

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

Following concepts demonstrate different types of polymorphism in java.
1) Method Overloading
2) Method Overriding

Method Definition:
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name.

1)Method Overloading:

In Java, it is possible to define two or more methods of same name in a class, provided that there argument list or parameters are different. This concept is known as Method Overloading.

If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.Different ways to overload the method

There are two ways to overload the method in java

  • By changing number of arguments
  • By changing the data type
1)Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.

2)Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.


2)Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Rules for Java Method Overriding

  • method must have same name as in the parent class
  • method must have same parameter as in the parent class.
  • must be IS-A relationship (inheritance).
Example of method overriding


About admin

Check Also

Internal Working of HashMap in Java

In this article, we will see how hashmap’s get and put method works internally. What ...

Leave a Reply