例:
Using overloaded methods
public class MethodOverload {
public static void main(String[] args) {
System.out.println("The square of integer 7 is " + square(7));
System.out.println(" The square of double 7.5 is " + square(7.5));
}
System.out.println("The square of integer 7 is " + square(7));
System.out.println(" The square of double 7.5 is " + square(7.5));
}
public static int square(int x) {
return x * x;
}
return x * x;
}
public static double square(double y) {
return y * y;
}
}
return y * y;
}
}
满足以下条件的两个或多个方法构成“重载”关系:
(1)方法名相同
(2)参数类型不同,参数个数不同或者参数类型的顺序不同
像System.out.println一样,就是重载的。
所以当实参类型是整型,那么系统会相应的调用形参同样是整型的int square(int x)方法;当实参类型是浮点型,那么系统会相应的调用形参同样是整型的int square(double y)方法;
方法调用跟形参变量名(x,y)没有关系,与形参类型有关。