java学习--第十一天(补充1)

15 篇文章 0 订阅
15 篇文章 0 订阅

 原视频地址:【零基础 快速学Java】韩顺平 零基础30天学会Java 


Java基础-方法之重载及可变参数

方法之重载

什么是重载?

在同一个类中,多个同名方法的存在,但要求形参列表不一致

示例代码

public class hello01 {
	public static void main(String[] args) {
		MyCaculate cl = new MyCaculate();
		System.out.println(cl.caculate(1,2.0));

	}
}
class MyCaculate{
	public int caculate(int n1, int n2){
		return n1 + n2;
	}
	public double caculate(int n1, double n2){
		return n1 + n2;
	}
	public int caculate(int n1, int n2, int n3){
		return n1 + n2 +n3;
	}
	public double caculate(double n1, int n2, int n3){
		return n1 + n2 +n3;
	}
}

方法重载detail
  1. 方法名:必须相同
  2. 形参列表:必须有不同(形参类型,或个数,或顺序;至少有一样不同,参数名无要求)
  3. 返回类型:无要求

小案例

public class hello01 {
	public static void main(String[] args) {
		Methods me = new Methods();
		System.out.println(me.max(23.75,5.01,18.01));
	}
}
class Methods{
	public int max(int n1 , int n2){
		if(n1 > n2){
			return n1;
		}else{
			return n2;
		}
	}
	public double max(double n1 , double n2){
		return n1 > n2 ? n1 : n2;
	}
	public double max(double n1 , double n2, double n3){
		return n1 > n2 ? (n1 > n3 ? n1 : n3) : (n2 > n3 ? n2 : n3);
		}
}

方法之可变参数

什么是可变参数?

可以把可变参数理解为重载的一个场景优化;

java允许将同一个类中 多个同名同功能参数个数不同的方法 封装成一个方法,就可以通过可变参数实现

如下方法的重载

class Methods{
	public int sum(int a, int b,){
		return a+b;
	}
	public int sum(int a, int b, int c){
		return a+b+c;
	}
	public int sum(int a, int b, int c,int d){
		return a+b+c+d;
	}
}

可变参数优化

public class hello01 {
	public static void main(String[] args) {
		Methods aa = new Methods();
		System.out.println(aa.sum(1,5,6));
	}
}
class Methods{
	public int sum(int... nums){
		int res = 0;
		for(int i=0;i< nums.length;i++){
			res += nums[i];
		}
		return res;
	}
}

可变参数
  1. 可变参数的实参可以为0个或任意多个

  2. 可变参数可以为数组

    public class hello01 {
    	public static void main(String[] args) {
    		int[] arr ={1,5,6};
    		Methods aa = new Methods();
    		System.out.println(aa.sum(arr));
    	}
    }
    class Methods{
    	public int sum(int... nums){
    		int res = 0;
    		for(int i=0;i< nums.length;i++){
    			res += nums[i];
    		}
    		return res;
    	}
    }
    

  3. 可变参数的本质就是数组

  4. 可变参数可以和普通类型的参数 一起放在形参列表,但必须保证可变参数在最后

    public void f2(String str , double... nums )

  5. 一个形参列表中只能出现一个可变参数

小综合

public class hello01 {
	public static void main(String[] args) {
		double[] arr ={98.5,90.2,93.2};
		Methods aa = new Methods();
		aa.scores("李华",arr);
	}
}
class Methods{
	public void scores(String str , double... score){
		double res = 0;
		for(int i = 0; i < score.length; i++){
			res += score[i];
			System.out.println(str + "同学,你"+ i +"门课程的总分="
			+ res);
		}

	}
}

  • 18
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值