Method Overloading Example Java Program
Definition
- A Class has multiple methods of the same name with different parameters is called Method overloading.
- This will allow one function call to perform different tasks depending on method parameters.
Syntax
public class OverloadClass {
public static void method(int num,int num2){ //Method for (int,int)
//Logic
}
public static void method(int num1,int num2,int num3){ //Method for (int,int,int)
//Logic
}
}
public class MainClass {
public static void main(String[] args){
OverloadClass A;
A.method(1,1); //for first Method
A.method(1,1,1); //for second Method
}
}
Method Overloading Example Program
class MethodOverloadingExample{
public void add(int num1,int num2){
int result1=num1+num2;
System.out.println("Result of first method is "+result1);
}
public void add(int num1,int num2,int num3){
int result2=num1+num2+num3;
System.out.println("Result of overloaded method is "+result2);
}
}
class MainMethodOverloading{
public static void main(String[] args){
MethodOverloadingExample obj=new MethodOverloadingExample();
obj.add(10,5);
obj.add(1,5,2);
}
}
Sample Output
Output is:
Result of first method is 15
Result of overloaded method is 8
OOPS Programs
- Encapsulation Example Java Program
- Single Inheritance Example Java Program
- Interface Example Java Program
- Multiple Inheritance Using Interface Example Java Program
- Multilevel Inheritance Example Java Program
- Hierarchical Inheritance Example Java Program
- Method Overloading Example Java Program
- Method Overriding Example Java Program
- Function or Method Overloading with different data type in Java
- Run Time Polymorphism Example Java Program
- Compile Time Polymorphism Example Java Program
- Abstract Class Example Java Program
Read More Articles
- Multiple Inheritance Using Interface Example Java Program
- Single Inheritance Example Java Program
- Multilevel Inheritance Example Java Program
- Hierarchical Inheritance Example Java Program
- Find all Substrings of a given string Example Java Program
- Create Matrix Example Java Program
- Sum Of Three Numbers Example Java Program
- Heap Sort Example Java Program
- Twin Prime Example Java Program
- Compile Time Polymorphism Example Java Program