【发布时间】:2017-04-24 00:46:48
【问题描述】:
我有一个项目,我正在创建一个带有 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 标头。
关于如何解决此问题的任何想法?
【问题讨论】:
-
您将不得不手动将字符串的前面从
super.toString()中剪掉。 -
如果您不想要超类的标题,请不要调用
super.toString() -
类有一个
accountType字段可能更合适,该字段会自动添加到字符串中,然后您就不需要覆盖它了。
标签: java