POLYMORPHISM IN JAVA

Prosper
2 min readJul 29, 2021

“Polymorphism” normally means having many forms. It is also the ability of a message to appear in more than one forms. Polymorphism is considered one of the most important aspects of OOP (Object Oriented Programming). ‘Poly’ means many and ‘morphs’ means forms.

TYPES OF JAVA POLYMORPHISM

1. Compile-time polymorphism: It is also known as static poolymorphism. This is the type that is achieved by function overloading or operator overloading. Java doesn’t support this.

Method Overloading

When there are multiple functions with the same namebut different parameters then these functions are said to overloaded.Functions can be overloaded by change in the number of agruments or change in type of arguments.

Example:

// Java program for Method overloading

class javapolymorphism{

// Method with 2 parameter

static int Multiply(int a, int b)

{

return a * b;

}

// Method with the same name but 2 double parameter

static double Multiply(double a, double b)

{

return a * b;

}

}

class Main {

public static void main(String[] args)

{

System.out.println(javapolymorphism.Multiply(2, 4));

System.out.println(javapolymorphism.Multiply(5.5, 6.3));

Output:

8
34.65

2. Runtime polymorphism: It is also known as Dynamic Method Dispatch. 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.

Example:

class mediumpost{

// Method with 2 parameter

static int Multiply(int a, int b)

{

return a * b;

}

// Method with the same name but 3 parameter

static int Multiply(int a, int b, int c)

{

return a * b * c;

}

}

class Main {

public static void main(String[] args)

{

System.out.println(mediumpost.Multiply(2, 4));

System.out.println(mediumpost.Multiply(2, 7, 3));

}

}

--

--