我希望有人能解释我是如何做出这个决定的。我知道,重载版本是根据声明的类型选择的,但是为什么在第二次调用时,决定是根据运行时类型做出的?
public class Test {
public static void main(String[] args) {
Parent polymorphicInstance = new Child();
TestPolymorphicCall tp = new TestPolymorphicCall();
tp.doSomething(polymorphicInstance);
// outputs: Parent: doing something...
call(polymorphicInstance);
// outputs: Child: I'm doing something too
}
public static void call(Parent parent){
parent.doSomething();
}
public static void call(Child child){
child.doSomething();
}
}
public class Parent {
public void doSomething() {
System.out.println("Parent: doing something...");
}
}
public class Child extends Parent{
@Override
public void doSomething() {
System.out.println("Child: I'm doing something too");
}
}
public class TestPolymorphicCall {
public void doSomething(Parent p) {
System.out.println("Parent: doing something...");
}
public void doSomething(Child c) {
System.out.println("Child: doing something...");
}
}
提前致谢!