我正在尝试将抽象类的子类对象存储在数组中。
我没有收到错误消息,但在调用打印数组信息时,我只看到最后一个用户输入帐户的5个重复项。但是,在输入数据时,在提示输入时,每个输入的输出是唯一的。我认为嵌套在for循环中的if / else语句中出现了问题(如下所示)。
为了节省空间,我的代码将略有删节。
编辑1:这是我的第一个问题,如果我能改进它,请告诉我!
// BankAccountTest
public class BankAccountTest {
int numAccHolders = in.nextInt();
BankAccount[] bankaccounts = new BankAccount[numAccHolders];
BankAccount.generateAccountDetails(bankaccounts, numAccHolders);
// BankAccount
public abstract class BankAccount {
protected static double balance;
protected static int accNum;
protected static int accType;
public BankAccount(double balance, int accNum, int accType){
this.balance = balance;
this.accNum = accNum;
this.accType = accType;
}
public getBalance(){
return balance;
}
public getAccNumber(){
return accNumber;
}
public static void generateAccountDetails(BankAccount[] bankaccounts,
int numAccHolders){
for(int i = 0; i < numAccHolders; i++){
accNum = (i + 1);
int accType = in.nextInt();
double balance = in.nextDouble();
if(accType == 1){
bankaccounts[i] = new ChequingsAccount(balance, accNum, accType);
} else if (accType == 2) {
bankaccounts[i] = new SavingsAccount(balance, accNum, accType);
}
// ChequingsAccount
public class ChequingsAccount extends BankAccount {
public ChequingsAccount(double balance, int accNum, int accType)
super(balance, accNum, accType);
// SavingsAccount
public class SavingsAccount extends BankAccount {
public SavingsAccount(double balance, int accNum, int accType)
super(balance, accNum, accType);
BankAccount.balance
,BankAccount.accNum
,BankAccount.accType
属性不应该是静态的。它们在所有实例之间共享。