该程序使用方法重载查找两个,三个和四个数字的总和。这里我们有三个具有相同名称add()的方法,这意味着我们正在重载此方法。根据我们在调用add方法时传递的参数数量,将确定将调用哪个方法。
示例:使用“方法重载”查找多个数字之和的程序
首先,add()方法有两个参数,这意味着当我们在调用add()方法时传递两个数字时,将调用此方法。类似地,当我们传递三个和四个参数时,将分别调用第二个和第三个add方法。
public class JavaExample{ int add(int num1, int num2) { return num1+num2; } int add(int num1, int num2, int num3) { return num1+num2+num3; } int add(int num1, int num2, int num3, int num4) { return num1+num2+num3+num4; } public static void main(String[] args) { JavaExample obj = new JavaExample(); //This will call the first add method System.out.println("Sum of two numbers: "+obj.add(10, 20)); //This will call second add method System.out.println("Sum of three numbers: "+obj.add(10, 20, 30)); //This will call third add method System.out.println("Sum of four numbers: "+obj.add(1, 2, 3, 4)); }}输出:
Sum of two numbers: 30Sum of three numbers: 60Sum of four numbers: 10
