3
我希望有人會解釋我是如何做出這個決定的。我明白,重載版本是根據聲明的類型選擇的,但爲什麼在第二次調用時,是根據運行時類型做出的決定?
超載和多態性
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...");
}
}
提前感謝!
謝謝,我有點困惑自己這個棘手的例子,因爲TestPolymorphicCall類方法根本不調用參數的引用。但是你是對的,不管重載版本的方法叫做**,它是基於聲明的類型**選擇的,當處理多態類型時,調用的行爲是子類型1。 –