- 重载:重复负载,方法名相同,参数列表不同 (参数个数不同或者参数类型不同,但并不考虑参数名,仅仅是参数名不同的时候不叫重载)
- 参数个数不同
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