java中棘手的方法重载
class ABC {
void doMe(String s) {
System.out.println("String");
}
}
class XYZ extends ABC {
void doMe(Object o) {
System.out.println("Object");
}
}
public class StopStart {
public static void main(String[] args){
ABC o = new XYZ();
o.doMe(null);
}
}
会发生什么,为什么? 字符串类扩展对象。那么将执行哪个doMe()。 这是编译错误吗
# 1 楼答案
重载是在编译时根据变量
o
的编译时类型解决的。因此,在XYZ
子类中定义哪些方法并不重要。只有ABC
的方法是相关的因此,编译器只考虑
void doMe(String s)
,这就是所选择的方法