What is Method overloading?
class calc
{
void add(int a,int b)
{
System.out.pritnln(a+b);
}
void add(int a,int b,int c)
{
System.out.pritnln(a+b+c);
}
public static void main(String args[])
{
calc obj1=new calc();
obj1.add(10,20,30);
obj1.add(10,20);
}
}
OUTPUT:60
30
--------------------------------------------------------------
Example 2: Difference in data type of argument
class calc
{
void add(int a,int b)
{
System.out.pritnln(a+b);
}
void add(float a,float b )
{
System.out.pritnln(a+b);
}
public static void main(String args[])
{
calc obj1=new calc();
obj1.add(10.5,10.5)
obj1.add(10,20);
}
}
A class is have two or more methods having same name,but their argument lists are different(Number of Parameters,data type of paraameters,Sequence of Data type of parameters) it is called method overloading.
It is also known as Static Polymorphism.
Advantages: It increases the readability of the program
--------------------------------------------------------------
Example 1: Different number of parameters in the argument listclass calc
{
void add(int a,int b)
{
System.out.pritnln(a+b);
}
void add(int a,int b,int c)
{
System.out.pritnln(a+b+c);
}
public static void main(String args[])
{
calc obj1=new calc();
obj1.add(10,20,30);
obj1.add(10,20);
}
}
OUTPUT:60
30
--------------------------------------------------------------
Example 2: Difference in data type of argument
class calc
{
void add(int a,int b)
{
System.out.pritnln(a+b);
}
void add(float a,float b )
{
System.out.pritnln(a+b);
}
public static void main(String args[])
{
calc obj1=new calc();
obj1.add(10.5,10.5)
obj1.add(10,20);
}
}
OUTPUT:21
30
30
--------------------------------------------------------------