在学习重载部分的ppt中,我发现了一些问题,在这里记录一下
1. 重载的必要条件是参数列表的不同!
ppt原话有这么一句:
重载:多个方法具有同样的名字,但有不同的参数列表或返回值类型
这句话的意思似乎是“不同的参数列表”与“不同的返回值类型”两者择其一即可,但事实上参数列表的不同是必要条件,比如下面代码:
public class Test1 implements Test{
@Override
public void myprint() {
System.out.println("2222");
}
public boolean changeSize(int size, String name, float pattern) {
return true;
}
public void changeSize(int size, String name, float pattern) {
return;
}
public static void main(String[] args) {
new Test1().test();
}
}
这段代码是会报错的,提示:
Duplicate method changeSize(int, String, float) in type Test1
事实上,对于重载, 不同的参数列表是必要的,而不同的返回值类型,不同的修饰符,不同的异常都是可选的。
2. 重载执行的方法是在编译阶段时决定的
这一个属性看似没有什么价值,但是在特殊情况下,它却是很能迷惑人的一点。
观察下面的代码:
<