Method Overloading In Java

If there are multiple methods in a class with same name and different parameters ,then it is called method overloding .

If we have to perform same operation but with different arguments ,we use method overloading to increase the readability of the program.

For example, if we have to perform addition operation of different numbers i.e add of 2 numbers or add of three numbers. Then we have to make a method sum(int x,inty).When we make a method of adding three number we also make a method with diffrent name then how user would know that it is a sum method .So for increasing the readibility of program we use method overloading.

There are 2 ways of method overloading.
1-by changeing no of parameters
2-by changing datatype

EXAMPLE OF METHOD OVERLOADING BY CHANGING PARAMETERS

class A
{
void sum(int x,int y)
{
System.out.println(x+y);
}
void sum(int x,int y,int z)
{
System.out.println(x+y+z);
}
public static void main(String args[])
{
A ob=new A;
ob.sum(5,6,7);
ob.sum(5,6);
}
}
OUTPUT
18
11

EXAMPLE OF METHOD OVERLOADING BY CHANGING DATATYPE

class A
{
void sum(int x,int y)
{
System.out.println(x+y);
}
void sum(double x,double y)
{
System.out.println(x+y);
}
public static void main(String args[])
{
A ob=new A;
ob.sum(5.5,5.5);
ob.sum(5,5);
}
}
OUTPUT
11
10

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *