从子类调用超类方法

时间:2017-07-20 16:08:59

标签: java inheritance subclass superclass bank

我正在使用超类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);
            }
    }

4 个答案:

答案 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

中的

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{...}