Polymorphism in Java

Polymorphism in java is the ability of an entity to take several forms or performing single action at different times. As it was named Poly means many and morph means one or more forms, so that we can know polymorphism means many forms. Which means an object showing different behaviors at different times. For example, a person can be a son, student, employee, husband, and father, he is playing different roles in the different situation he is changing the behavior according to the point of the time.

Polymorphism is often classified into two types

  1. Static Polymorphism (Compile time polymorphism)
  2. Dynamic Polymorphism (Runtime polymorphism)

Static Polymorphism

The static polymorphism will be resolved during the compiler time so that it was also called the Compile time Polymorphism. The Method Overloading is an example of Static Polymorphism.

Method Overloading

It is possible to create a method that has the same name but different in the parameter list and the number of arguments passed is called Method Overloading.

Method Overloading is used when objects are required to perform a similar task but use in different input parameters when we call a method in an object java matches up the method name first and then the number and types of the parameters to decide which one of the definitions to execute.

For Example:

import java.io.*;
class Overload1
{
void test()
{
System.out.println(“Method Overloading”);
}
void test(int a)
{
System.out.println(“Single Value =” +a);
}
int test(int a,int b)
{
return(a*b);
}
double test(double a)
{
return(a*a);
}
}
class Overload
{
public static void main(String args[])throws IOException
{
Overload1 t=new Overload1();
t.test();
t.test(10);
System.out.println(“Value of a*b =”+t.test(10,20));
System.out.println(“Value of a*a =”+t.test(10.5));
}
}

Output:

Method Overloading
Sing Value = 10
Value of a*b = 200
Value of a*a = 110.25

Dynamic Polymorphism

The dynamic polymorphism in java will be resolved during the runtime so that it was also called the Runtime Polymorphism. The Method Overriding is an example of Dynamic Polymorphism.

Method Overriding

A method defined in the superclass is inherited by its subclasses and used by the object created by the subclass.

It is possible to define a method in a subclass that has the same name, the same number of arguments and, the same return type as a method in the superclass.

For Example:

import java.io.*;
class Parent
{
void display()
{
System.out.println(“This is Parent Class”);
}
}
class Child extends Parent
{
void display()
{
super display();
System.out.println(“This is Child Class”);
}
}
Class Override
{
public static void main(String args[])throws IOException
{
Child c= new Child();
c.display();
}
}

Output:

This is Child Class

Related Article: https://codingsmania.in/inheritance-in-java/

Leave a Reply