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