Polymorphism in JAVA - Compile and Runtime polymorphism - Unleash-Coding-Skills

Sunday, 3 June 2018

Polymorphism in JAVA - Compile and Runtime polymorphism



Polymorphism in JAVA:

Polymorphism in Java is a concept by which we can perform a single action by different ways. 

Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. 

Polymorphism is of two types
 1) Compile Time Polymorphism or Method Overloading
.2) Runtime Polymorphism or Method Overriding.

First of all, we can go through compile-time polymorphism it is simply defined as follows:

Methods having the same name but have had different parameters numbers or different parameter types. We can go through Compile time polymorphism with two different cases. Methods having the same name and a same number of parameters but with different data types.

class UCS
{
public void test1(int a,int b)
{
System.out.println("The numbers are " + a +" "+b);
}
public void test1(int a,double b)
{
System.out.println("The numbers are "+a+" "+b);
}
}

public class Overloading
{
public static void main(String args[])
{
UCS obj = new UCS();
obj.test1(2,3);
obj.test1(1,1.2);
}
}

Output:
The numbers are 2 3
The numbers are 1 1.2

In the first obj.test1 call it calls the function that has the matching of format test1(int.., int ..)
In the second obj.test1 call it calls the function that has the matching of format test1(int.., float)



So In this way the compile-time polymorphism i.e., function overloading is implemented with the same number of the parameters but with different data types.

Know we can go through the second case:
Methods have a different number of the parameters with the same name. The data types of the parameters may be similar or different. Both come under compile time polymorphisms in java.

class UCS
{
public void test1(int a,int b)
{
System.out.println("The numbers are " + a +" "+b);
}

public void test1(int a,int b,int c)
{
System.out.println("The numbers are "+a+" "+b+" "+c);
}
}

public class Overloading
{
public static void main(String args[])
{
UCS obj = new UCS();
obj.test1(2,3);
obj.test1(1,2,3);
}
}

Output:
The numbers are 2 3
The numbers are 1 2 3

Here we can observe that first obj.test1 is calling the method in the class UCS of the declaration of type
test1(int.., int ..)
And the second obj.test1 is calling of the method in the UCS of the declaration of type
 test1(int.., int.., int ..)
Here we completed one part of polymorphism which is a compile type polymorphism or Method overloading.
Next, we can go through Runtime polymorphism in details in the following link as below.

https://www.unleashcodingskills.com/2018/06/runtime-polymorphism-java-polymorphism.html


No comments:

Post a comment