我已經搜索了一個解決方案,但我仍然不明白在這裏要做什麼。這個程序應該模仿一個atm機器,它會從支票中扣除餘額併爲存款添加資金。從父類的對象的數組列表中調用子類的方法
我有這個父類:
public class Transaction
{
private int transNumber;
private int transId;
private double transAmt;
public Transaction(int number, int id, double amount)
{
transNumber = number;
transId = id;
transAmt = amount;
}
public int getTransNumber()
{
return transNumber;
}
public int getTransId()
{
return transId;
}
public double getTransAmount()
{
return transAmt;
}
}
我具有存儲事務的對象,每戒斷/存款陣列列表(transList)。
子類:
public class Check extends Transaction
{
private int checkNumber; // check number for each check transaction
public Check(int tId, double tAmt, int tCount, int checkNumber) {
super(tCount, tId, tAmt);
this.checkNumber = checkNumber;
}
public int getCheckNumber() {
return checkNumber;
}
public void setCheckNumber(int checkNumber) {
this.checkNumber = checkNumber;
}
}
我需要做的是打印出的JOptionPane的支票號碼,如果用戶要求他們。
在主,我有:
checkNumStr = JOptionPane.showInputDialog("Enter check number:");
checkNum = Integer.parseInt(checkNumStr);
checkAmtStr = JOptionPane.showInputDialog("Eneter check amount:");
checkAmt = Double.parseDouble(checkAmtStr);
Check c = new Check(1, checkAmt, acctCheck.gettransCount(), checkNum);
acctCheck.addTrans(c);
我不知道我是否已經足夠清晰。我以前沒有在這裏提過一個問題。我需要知道的是如何從父類Transaction的對象的數組列表中調用Check.getCheckNumber()。
編輯:transList位於另一個類:支票帳戶:
public class CheckingAccount extends Account
{
private double totalServiceCharge;
private static ArrayList<Transaction> transList;
// keeps a list of Transaction objects for the account
private int transCount = 0;
// the count of Transaction objects and used as the ID for each transaction
NumberFormat fmt = NumberFormat.getCurrencyInstance();
public CheckingAccount()
{
transList = new ArrayList<Transaction>();
totalServiceCharge = 0;
}
public double getServiceCharge()
{
return totalServiceCharge;
}
public void setServiceCharge(double currentServiceCharge)
{
totalServiceCharge += currentServiceCharge;
}
// adds a transaction object to the transList
public void addTrans(Transaction newTrans)
{
transList.add (newTrans);
transCount++;
}
//returns the current value of transCount;
public int gettransCount()
{
return transCount;
}
}
答案是 - 不要這樣做。你的Transaction類不應該擁有這個ArrayList,因爲它屬於其他地方,而不是父類。 –