Method Overloading in Java | Static Polymorphism

Method Overloading is a feature that allows a class to have more than one method having the same name but different in parameters. Method Overloading is an example of Static and Compile Time Polymorphism (Polymorphism: having more than one form).

Two ways to overload a method

1.  Number of parameters.

For example: add(int, int)

add(int, int, int)

Example: Here in this example, we are performing addition of two numbers and three numbers using the concept of method overloading.

class Addittion{ 

int add(int a,int b)

{

return a+b;

}  

int add(int a,int b,int c)

{

return a+b+c;

}  } 

class TestOverloading{ 

public static void main(String[] args){ 

Addition obj= new Addition( );

System.out.println(obj.add(11,11)); 

System.out.println(obj.add(11,11,11)); 

}} 

Output:

 22

33

2. Data type of parameters.

For example:

add(int, int)

add(int, float)

Example:

class Addition{ 

int add(int a, int b)

{

return a+b;

} 

double add(double a, double b)

{

return a+b;

} 

} 

class TestOverloading{ 

public static void main(String[] args){ 

Addition obj= new Addition( );

System.out.println(obj.add(11,11)); 

System.out.println(obj.add(12.3,12.6)); 

}} 

Output:

22

24.9

 

Advantage of method overloading

Method overloading increases the readability of the program.


No comments:

Post a comment

All about journals and research paper | What is impact factor? | how the impact factor is calculated? | who calculate the impact factor? Scopous journals

Figure 1: One of my Research Papers When the Scholars are in their Master or PhD or in any research field. They are supposed to writ...