Java重载

  • 重载:重复负载,方法名相同,参数列表不同 (参数个数不同或者参数类型不同,但并不考虑参数名,仅仅是参数名不同的时候不叫重载)
  • 参数个数不同
    public int add(int a,int b) {	
    		return a+b;
    	}
    	
    	public int add(int a,int b,int c) {	
    		return a+b+c;
    	}
    	
    

     

  • 参数类型不同
    public class Computer {
    
    		
    	public int add(int a,int b) {	
    		return a+b;
    	}
    	public double add(double a,int b) {	
    		return a+b;
    	}
    

     

  • 若仅仅是参数名不同,则会报错,下面的代码便会报错:
    public int add(int a,int b) {	
    		return a+b;
    	}
    	
    	public int add(int c,int d) {	
    		return c+d;
    	}
    

     

 

  • 若重载导致方法名相同,调用方法时如何确定到底调用的是哪个方法?判断方法:
  • 参数的个数
    package sirius;
    
    public class Computer {
    
    		
    	public int add(int a,int b) {	
    		return a+b;
    	}
    	
    	public double add(double a,int b) {	
    		return a+b;
    	}
    	
    
    	public int add(int a,int b,int c) {	
    		return a+b+c;
    	}
    	
    	public static void main(String[] args) {
    		
    		Computer c = new Computer();
    		int result =c.add(1, 2);
    	
    	}
    
    }
    

     

  • 数据类型
    package sirius;
    
    public class Computer {
    
    		
    	public int add(int a,int b) {	
    		return a+b;
    	}
    	
    	public double add(double a,int b) {	
    		return a+b;
    	}
    	
    	public int add(int a,int b,int c) {	
    		return a+b+c;
    	}
    	
    	
    
    	
    	
    	
    	public static void main(String[] args) {
    		
    		double x =c.add(1.0, 2);
    		System.out.println(x);
    	}
    
    }
    

     

 

 

  • this是一个代词,那个对象调用该方法,this就是谁:下面代码中是Student调用的test方法,则输出时this就是student的地址。
    package sirius;
    
    public class Student {
    
    	public void test() {
    		System.out.println("test方法:"+this);
    	}
    	
    	public static void main(String[] args) {
    		
    		Student student = new Student();
    		student.test();
    		System.out.println("main方法:"+student);
    	}
    
    }
    

    运行结果:

    test方法:sirius.Student@52e922
    main方法:sirius.Student@52e922
    

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值