本文共 1548 字,大约阅读时间需要 5 分钟。
目录
在一个类中,同名的方法如果有不同的参数列表(参数类型不同、参数个数不同甚至是参数顺序不同)则视为重载。同时,重载对返回类型没有要求,可以相同也可以不同,但不能通过返回类型是否相同来判断重载。
1.不同的含义:形参类型、形参个数、形参顺序不同
2.只有返回值不同不构成方法的重载
如:
int a(String str){}与 void a(String str){}
不构成方法重载
3.只有形参的名称不同,不构成方法的重载
如:
int a(String str){}与int a(String s){}
不构成方法重载
public class Test { public static void main(String[] args) { System.out.println(add(3, 5));// 8 System.out.println(add(3, 5, 10));// 18 System.out.println(add(3.0, 5));// 8.0 System.out.println(add(3, 5.0));// 8.0 // 我们已经见过的方法的重载 System.out.println();// 0个参数 System.out.println(1);// 参数是1个int System.out.println(3.0);// 参数是1个double } /** 求和的方法 */ public static int add(int n1, int n2) { int sum = n1 + n2; return sum; } // 方法名相同,参数个数不同,构成重载 public static int add(int n1, int n2, int n3) { int sum = n1 + n2 + n3; return sum; } // 方法名相同,参数类型不同,构成重载 public static double add(double n1, int n2) { double sum = n1 + n2; return sum; } // 方法名相同,参数顺序不同,构成重载 public static double add(int n1, double n2) { double sum = n1 + n2; return sum; } //编译错误:只有返回值不同,不构成方法的重载 public static double add(int n1, int n2) { double sum = n1 + n2; return sum; } //编译错误:只有参数名称不同,不构成方法的重载 public static int add(int n2, int n1) { double sum = n1 + n2; return sum; }}
运行效果:
转载地址:http://kkzr.baihongyu.com/