2013-08-02 18 views
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..."); 
     } 
    } 

提前感謝!

回答

4

類引用是指兒童類對象:

Parent polymorphicInstance = new Child(); 

所以,當你通過在調用方法的引用,調用實際的方法是具有家長參數類型只要。但是,當你調用方法doSomething(),在參考:

public static void call(Parent parent){ 
    parent.doSomething(); 
} 

它將調用doSomething()方法,您在兒童類已重寫。


這是多態性的經典案例。假設你有一個類形狀圈子,它覆蓋形狀類中定義的方法calculateArea()

Shape circle = new Circle(); 
// This will invoke the method in SubClass. 
System.out.println(circle.calculateArea()); 

當你重寫子類超類的方法,然後調用實際的方法是在運行時決定,基於什麼實際的對象的超類的參考點上。這稱爲方法調用的動態調度

+0

謝謝,我有點困惑自己這個棘手的例子,因爲TestPolymorphicCall類方法根本不調用參數的引用。但是你是對的,不管重載版本的方法叫做**,它是基於聲明的類型**選擇的,當處理多態類型時,調用的行爲是子類型1。 –