被重载的方法必须具有不同的参数列表.不能基于不同修饰符或返回值类型来重载方法.
package welcome; public class TestMethodOverloading {
public static void main(String[] args) {
System.out.println("The maximum between 3 and 4 is " + max(3, 4)); // 调用max(int, int)方法 System.out.println("The maximum between 3.0 and 5.4 is " + max(3.0, 5.4)); // 调用max(double, double)方法 System.out.println("The maximum between 3.0 , 5.4 and 10.14 is " + max(3.0, 5.4, 10.14)); // 调用max(double, double, double)方法
} public static int max(int num1, int num2){
if(num1 > num2){
return num1;
}else{
return num2;
}
} public static double max(double num1, double num2){
if(num1 > num2){
return num1;
}else{
return num2;
}
} public static double max(double num1, double num2, double num3){
return max(max(num1,num2), num3);
}
}
package welcome; /*
*演示歧义调用
* 当调用一个方法时,有一个或者更多可能的匹配,编译器无法判断哪个匹配更精确,这称为歧义调用.
* 歧义调用会引发编译错误
*/
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1,2)); // max(int, double)和max(double, int)都有可能与max(1,2)匹配,由于这两个方法谁也不比谁更精确
} // 所以这个调用是有歧义的,将引发编译错误 public static double max(int num1, double num2){
if(num1 > num2){
return num1;
}else{
return num2;
}
} public static double max(double num1, int num2){
if(num1 > num2){
return num1;
}else{
return num2;
}
}
}