Java——方法重载
方法的重载是指一个类中可以定义有相同的名字,但参数不同的多个方法。调用时,会根据不同的参数表选择对应的方法。
首先先简单写一个TestOverload类,再此类中写出一个比较int的方法max
void max(int a , int b) {
System.out.println(a > b ? a : b);
}
此时如果还想再进行float的大小比较则需要再写一个方法`
void max1(float c , float d ) {
System.out.println(a > b ? a : b);
}
但是在main方法中,输入的变量为了比较大小则要分别判定自己的类型(int或者float),这时将要用到重载这个方法。
public class TestOverload {
void max(int a , int b) {
System.out.println(a > b ? a : b);
}
void max(float c , float d ) {
System.out.println(a > b ? a : b);
}
public static void main(String[] args) {
TestOverload t = new TestOverload();
t.max(3, 4);
}
通过使用重载来对输入的变量自动选择适当的方法。
这时候再加上一个short方法会发生什么呢?
void max(short a , short b) {
System.out.println("short");
System.out.println(a > b ? a : b);
}
我们在main中使得输入的变量固定为short类型
short a = 3;
short b = 4;
t.max(a, b);
同时再将short方法中加入一条输出语句来让我们更清楚地看到此方法是否被调用。
void max(short a , short b) {
System.out.println("short");
System.out.println(a > b ? a : b);
}
最后我们来对整体程序进行调试
public class TestOverload {
void max(int a , int b) {
System.out.println(a > b ? a : b);
}
void max(short a , short b) {
System.out.println("short");
System.out.println(a > b ? a : b);
}
void max(float c , float d ) {
System.out.println(a > b ? a : b);
}
public static void main(String[] args) {
TestOverload t = new TestOverload();
t.max(3, 4);
short a = 3;
short b = 4;
t.max(a, b);
}
![调试结果](https://img-blog.csdnimg.cn/20200925200250934.png#pic_center)
}