Java - 14 方法重载+可变参数

Java - 14 方法重载+可变参数

方法重载

Java允许同一个类中,多个同名方法存在,但要求形参列表不一致(类型,顺序),返回类型没有要求

public class Overload{
	public static void main(String[] args) {
		MyCalculator m = new MyCalculator();
		System.out.println(m.calculate(1,2));
	}

}

class MyCalculator {
	public int calculate(int n1, int n2){
		return n1+n2;
	}

	public double calculate(int n1, double n2){
		return n1+n2;
	}

	public double calculate(double n1, int n2){
		return n1+n2;
	}

	public double calculate(double n1, double n2){
		return n1+n2;
	}
}

可变参数

Java允许将同一个类中多个同名同功能参数个数不同的方法,封装成一个方法

  • 可变参数本质是数组
public class VarParameters{
	public static void main(String[] args) {
		Methods m = new Methods();
		System.out.println(m.sum(1,2,3));
	}
}

class Methods{
	// 接收 0-n 个 int类型参数
	public int sum(int... nums){
		int res = 0;
		for(int i = 0; i<nums.length; i++){
			res += nums[i];
		}
		return res;
	}
}
  • 可变参数可以是数组
public class Test{
	public static void main(String[] args) {
		Methods m = new Methods();
		int[] arr = new int[3];
		System.out.println(m.sum(arr)); // 0
	}
}

class Methods{
	public int sum(int... nums){
		System.out.println("长度是:"+nums.length); // 3
		int res = 0;
		for(int i = 0; i<nums.length; i++){
			res += nums[i];
		}
		return res;
	}
}
  • 可变参数和普通类型的参数一起时,必须保证可变参数在最后
  • 一个形参列表中只能有一个可变参数
posted @   wajiez  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示