我正在使用超类Account
和子类SavingsAccount
建立一个无法透支的银行帐户。从主类调用makeWithdrawal()
方法时,应检查提取是否大于余额并提示输入,然后编辑余额。
如何从makeWithdrawal()
调用Account
方法并使用super关键字在SavingsAccount
中覆盖它?我的编译器给了我“错误:不兼容的类型:缺少返回值。
Account
中的方法:
double makeWithdrawal(double withdrawal) {
return balance -= withdrawal;
}
(非常简单。)这种方法最初是抽象的,但却导致错误。
SavingsAccount
中的方法:
public double makeWithdrawal(double withdrawal) {
double tempbalance = getBalance();
if (withdrawal > getBalance()) {
withdrawal = Input.getDouble("Your withdrawal cannot be larger than your balance. Enter a withdrawal <= "+getBalance());
return;
}
else {
return super.makeWithdrawal(withdrawal);
}
}
答案 0 :(得分:1)
问题不在于您致电super.makeWithdrawl()
,这是正确的。它位于上面return
子句中的空if
语句中。您获取更新提取金额的逻辑是明智的,但是当您这样做时需要返回新的余额。我建议只是将呼叫转移到条件之外的super.makeWithdrawl()
:
if(withdrawal > getBalance()) {
withdrawal = Input.getDouble("Your withdrawal cannot be larger than your balance. Enter a withdrawal <= "+getBalance());
}
return super.makeWithdrawal(withdrawal);
如果原始提款金额太大,这将使用更新的提款金额。
答案 1 :(得分:0)
if (withdrawal > getBalance()) {
withdrawal = Input.getDouble("Your withdrawal cannot be larger than your balance. Enter a withdrawal <= "+getBalance());
return;
}
你需要返回双值而不是简单的返回。
答案 2 :(得分:0)
问题在于
返回;
你应该用
替换它退货退货;
public double makeWithdrawal(double withdrawal) {
double tempbalance = getBalance();
if (withdrawal > getBalance()) {
withdrawal = Input.getDouble("Your withdrawal cannot be larger than your balance. Enter a withdrawal <= "+getBalance());
return withdrawal;
}
else {
return super.makeWithdrawal(withdrawal);
}
}
答案 3 :(得分:-1)
如果我理解正确的话:
Account是基类而SavingsAccount是子类?
然后:super.makeWithdrawal(withdrawal);
还要确保在定义类时继承:
public class SavingsAccount extends Account{...}