问:当子类继承父类后,子类中的方法,在父类中进行重载,那么在运行时是调用子类中的该方法还是父类中的该方法?
例子:
public class LessonProblem {
void test(int x) {
System.out.println("01 " +x);
}
public static void main(String[] args) {
Son a = new Son();
a.test(10);
}
}
class Son extends LessonProblem{
void test(double y) {
System.out.println("02 "+ y);
}
void test(int z) {
System.out.println("03 " +z);
}
}
在Son类和LessonProblem类中都有test(),初步猜想应该是调用Son类,因为对象调用顺序是子类→父类→Object类。
运行结果:03 10
注释掉test(int z)方法,运行结果:01 10
把参数改成10.1,运行结果:02 10.1
由上可以很清楚地看到,当为整型时,会先在子类中找形参为整型的方法,如果找到了就调用;当没有整型的方法时,就到父类里找。