2012-01-02 95 views
1

我只是想確保我做的是正確的事情。我有一個子賬戶,然後兩個子類SavingsAccount和CreditAccount,我想將它們存儲在一個ArrayList,但是當我做這樣我得到的錯誤將對象添加到列表中?

List<Account> accountList = new ArrayList<Account>(); 
// creditaccount 
Account account = new CreditAccount(); 
list.add(account); 

// savingsaccount 
Account account = new SavingsAccount(); 
list.add(account); 

我想我可能只是增加他們這樣,但我猜一定有這樣一個獨特的名字...

Account account1 = new SavingsAccount(); 
list.add(account1); 

...或者我誤解了它嗎?我對此很陌生,所以幫助我保持警惕!謝謝!

回答

5

你是對的,變量名在其給定範圍內是唯一的(本地in-method與實例變量)。然而,因爲這是面向對象的,你可以重複使用的變量,因爲它只是引用給定對象:

List<Account> accountList = new ArrayList<Account>(); 
// creditaccount 
Account account = new CreditAccount(); 
list.add(account); // <-- adds the creditAccount to the list 

// savingsaccount 
account = new SavingsAccount(); // <-- reuse account 
list.add(account); // <-- adds the savingsAccount to the list 

就個人而言,我不喜歡這種做法,並願意使用不言自明的名字,如:

Account creditAccount = new CreditAccount(); 
Account savingsAccount = new SavingsAccount(); 
... 
list.add(creditAccount); 
list.add(savingsAccount); 

更新1: 如果沒有進一步的初始化帳戶對象,你可能只是這樣做:

list.add(new CreditAccount()); 
list.add(new SavingsAccount()); 

更新2: 我忘了提,有一個「更高級的」使用匿名內部模塊,使您可以聲明一個變量不止一次的方法中的方法:

void someMehtod() { 
    List<Account> accountList = new ArrayList<Account>(); 

    { // <-- start inner block 
     Account account = new CreditAccount(); 
     accountList.add(account); 
    } // <-- end inner block 

    { 
     Account account = new SavingsAccount(); 
     accountList.add(account); 
    } 

    account.toString() // compile time error as account is not visible! 

} 
+0

所以,如果我第一次申報這樣的:帳戶帳戶;然後:account = new CreditAccount();和account = new SavingsAccount();我可以使用相同的變量帳戶 – 2012-01-02 09:37:03

+0

回覆您上次的編輯:然後我必須爲每個變量聲明一個賬戶,如:Account creditAccount;和賬戶儲蓄賬戶; ? – 2012-01-02 09:38:52

+0

是的,但您必須使用前一個帳戶對象,否則在分配新對象時將覆蓋該引用。如果你一般不熟悉這種方法或面向對象的方法,我建議你做一些簡單的測試來理解這個概念。使用類如java.lang.String。 (回答你的第一條評論)。 – home 2012-01-02 09:40:11

2

帳戶的帳戶=新SavingsAccount ();
這會給編譯時錯誤。您無法申報帳戶兩次。 將以上聲明更改爲 account = new SavingsAccount();