我有一个项目,我正在创建一个带有SavingsAccount子类的BankAccount超级克拉。一切正常,但我无法返回我特别想要的字符串。
示例:(修剪下来)
public class BankAccount {
public static final double MONTHS_IN_YEAR = 12.0;
private String myCustomerName;
private double myAccountBalance;
private double myInterestRate;
protected int myMonthlyWithdrawCount;
protected double myMonthlyServiceCharges;
public BankAccount(final String theNameOfOwner,
final double theInterestRate) {
myCustomerName = theNameOfOwner;
myAccountBalance = 0.0;
myInterestRate = theInterestRate;
myMonthlyWithdrawCount = 0;
myMonthlyServiceCharges = 0.0;
}
public String toString() {
String result = "";
result += String.format("BankAccount[owner: %s, balance: %.2f,",
myCustomerName, myAccountBalance);
result += String.format(" interest rate: %.2f,", myInterestRate);
result += String.format("\n\t\t ");
result += String.format("number of withdrawals this month: %d,",
myMonthlyWithdrawCount);
result += String.format(" service charges for this month: %.2f]",
myMonthlyServiceCharges);
return result;
}
}
驱动程序类将使用BankAccount的toString方法并打印它:
BankAccount[owner: John Doe, balance: 0.00, interest rate: 0.05,
number of withdrawals this month: 0, service charges for this month: 0.00]
(这对于这个超类非常适合)
但是,这里有子类SavingsAccount
public class SavingsAccount extends BankAccount {
public static final double SAVINGS_THRESHOLD = 25.0;
private boolean myStatusIsActive;
public SavingsAccount(final String theNameOfOwner,
final double theInterestRate) {
super(theNameOfOwner, theInterestRate);
myStatusIsActive = false;
if (super.getBalance() >= SAVINGS_THRESHOLD) {
myStatusIsActive = true;
}
}
public String toString() {
String result = "";
result += "SavingsAccount";
result += super.toString();
return result;
}
}
调用SavingsAccount的toString方法时,会打印:
SavingsAccountBankAccount [所有者:Dan Doe,余额:0.00,利率:0.05, 本月提款数量:0,本月服务费:0.00]
(我不想要包含BankAccount
,我只是希望它打印" SavingsAccount
"标题然后直接转到"[owner: Dan Doe,"
}
我试过让它回归" SavingsAccount
"首先它正确地执行,但是当调用super.toString()时,它也最终返回我不想要的BankAccount
标题。
关于如何解决此问题的任何想法?
答案 0 :(得分:4)
我能想到的一些选择:
将“BankAccount”替换为“SavingsAccount”,而不是仅仅添加它:
@Override
public String toString() {
return super.toString().replaceFirst("BankAccount", "SavingsAccount");
}
将详细信息部分移动到自己的方法中,并使用相应的标题从每个toString()
调用它:
// BankAccount.java
@Override
public String toString() {
return "BankAccount" + getDetailsString();
}
protected String getDetailsString() {
String result = String.format("[owner: %s, balance: %.2f,",
myCustomerName, myAccountBalance);
// ...
return result;
}
// SavingsAccount.java
@Override
public String toString() {
return "SavingsAccount" + getDetailsString();
}
在超类中获取运行时类名称,因此不需要完全覆盖它:
@Override
public String toString() {
String result = String.format("%s[owner: %s, balance: %.2f,",
getClass().getSimpleName(), myCustomerName, myAccountBalance);
// ...
return result;
}