2011-11-21 107 views
3

我遇到了一些課程工作問題,我試圖完成任何幫助,將不勝感激!在java中調用父類型時調用子方法

我有3種類型的帳戶,它們擴展了抽象類型「帳戶」。[CurrentAccount,StaffAccount和MortgageAccount]。

我想從文件中讀取一些數據,並創建帳戶對象以及用戶對象添加到存儲在程序中的hashmaps。

當我創建帳戶對象我使用類型賬戶的臨時變量和定義其亞型依賴於讀出的數據

例如:

Account temp=null; 

if(data[i].equalsIgnoreCase("mortgage"){ 
    temp= new MortgageAccount; 
} 

問題是當我嘗試調用屬於類型MortgageAccount的方法。

我是否需要每種類型的臨時變量,StaffAccount MortgageAccount和CurrentAccount,並使用它們coresspondingly以使用他們的方法?

在此先感謝!

+0

是的,你需要有每個類型的臨時變量。你不能通過家長的參考調用孩子的方法。或者你必須將對象轉換成它的子類型,然後你可以調用它的方法。 – Naved

回答

7

這取決於。如果父級Account有一個覆蓋MortgageAccount的方法,那麼當您調用該方法時,您將獲得MortgageAccount版本。如果該方法僅存在於MortgageAccount中,則需要轉換該變量以調用該方法。

4

所有你需要的是一個MortgageAccount類型的對象來調用它的方法。您的對象temp的類型爲MortgageAccount,因此您可以在該對象上調用MortageAccountAccount方法。不需要鑄造。

+0

這是Eclipse/API顯示哪裏沒有錯誤的情況嗎?我無法編譯atm來測試它是否可以在未被投射的情況下調用孩子的方法。 – JohnDoe

4

這是Dynamic method dispatch

概念如果使用基類的參考變,使派生類的對象,那麼您可以僅被定義或在基類至少聲明和要覆蓋他們的訪問方法在派生類中。

要調用派生類的對象,您需要派生類的引用變量。

5

如果您的所有帳戶對象具有相同的接口,意味着它們聲明相同的方法,並且它們僅在實現方式上有所不同,那麼您不需要每種類型的變量。

但是,如果您想調用特定於子類型的方法,那麼您需要一個該類型的變量,或者在調用該方法之前需要先轉換該引用。

class A{ 
    public void sayHi(){ "Hi from A"; } 
} 


class B extends A{ 
    public void sayHi(){ "Hi from B"; 
    public void sayGoodBye(){ "Bye from B"; } 
} 


main(){ 
    A a = new B(); 

    //Works because the sayHi() method is declared in A and overridden in B. In this case 
    //the B version will execute, but it can be called even if the variable is declared to 
    //be type 'A' because sayHi() is part of type A's API and all subTypes will have 
    //that method 
    a.sayHi(); 

    //Compile error because 'a' is declared to be of type 'A' which doesn't have the 
    //sayGoodBye method as part of its API 
    a.sayGoodBye(); 

    // Works as long as the object pointed to by the a variable is an instanceof B. This is 
    // because the cast explicitly tells the compiler it is a 'B' instance 
    ((B)a).sayGoodBye(); 

}