你是對的,變量名在其給定範圍內是唯一的(本地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!
}
所以,如果我第一次申報這樣的:帳戶帳戶;然後:account = new CreditAccount();和account = new SavingsAccount();我可以使用相同的變量帳戶 – 2012-01-02 09:37:03
回覆您上次的編輯:然後我必須爲每個變量聲明一個賬戶,如:Account creditAccount;和賬戶儲蓄賬戶; ? – 2012-01-02 09:38:52
是的,但您必須使用前一個帳戶對象,否則在分配新對象時將覆蓋該引用。如果你一般不熟悉這種方法或面向對象的方法,我建議你做一些簡單的測試來理解這個概念。使用類如java.lang.String。 (回答你的第一條評論)。 – home 2012-01-02 09:40:11