Polymorphism and method overloading

What is polymorphism?

Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.

Types of polymorphism:

In Java polymorphism is mainly divided into two types: 

  • Compile-time Polymorphism
  • Runtime Polymorphism

Compile-time polymorphism:

It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading[TBD]. 

Method Overloading:

When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in the number of arguments or/and a change in the type of arguments.(If we have to perform only one operation, having same name of the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.)

Different ways to overload the method:

There are two ways to overload the method in java

  1. By changing number of arguments
  2. By changing the data type

Advantage of method overloading:

Method overloading increases the readability of the program.

 Runtime polymorphism:

It is also known as Dynamic Method Dispatch[TBD]. 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.[TBD]

Reference:

https://www.javatpoint.com/method-overloading-in-java

https://www.javatpoint.com/runtime-polymorphism-in-java

https://www.geeksforgeeks.org/polymorphism-in-java/

https://www.geeksforgeeks.org/method-overloading-in-java/

Leave a comment

Design a site like this with WordPress.com
Get started