我只是想确保我做对了.我有一个子类帐户,然后是两个子类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);
Run Code Online (Sandbox Code Playgroud)
我想我可以像这样添加它们,但我想必须有这样一个独特的名字......
Account account1 = new SavingsAccount();
list.add(account1);
Run Code Online (Sandbox Code Playgroud)
......还是我误解了?我是新手,所以帮助我预先准备!谢谢!
你是对的,变量名在给定范围内是唯一的(本地方法与实例变量).然而,由于这是面向对象的,您可以重用该变量,因为它只引用给定的对象:
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
Run Code Online (Sandbox Code Playgroud)
就个人而言,我不喜欢这种方法,而是使用不言自明的名称,如:
Account creditAccount = new CreditAccount();
Account savingsAccount = new SavingsAccount();
...
list.add(creditAccount);
list.add(savingsAccount);
Run Code Online (Sandbox Code Playgroud)
更新1: 如果您不必进一步初始化帐户对象,您可以这样做:
list.add(new CreditAccount());
list.add(new SavingsAccount());
Run Code Online (Sandbox Code Playgroud)
更新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!
}
Run Code Online (Sandbox Code Playgroud)