java-如果方法是在超类中定义的,则如何根据调用它的对象更改结果

我有一个名为BankAccount的类(它是抽象定义的),这是我的超级类,还有两个子类,称为SavingsAccount和CheckingAccount.

它们都使用BankAccount中定义的提现方法,但是CheckingAccount可以透支,而SavingsAccount则不能.

我的问题是,如果在BankAccount构造函数中,我们包括以下内容:

public BankAccount(double balanceIn, double withdrawIn)
    {
        balance = balanceIn;
        withdraw = withdrawIn;
    }  

可以通过SavingsAccount类调用以下方法:

public SavingsAccount(double balanceIn, double withdrawIn)
    {
    // initialise instance variables
    super (balanceIn, withdrawIn);

    }

是否有一种方法可以根据是从CheckingAccount还是SavingsAccount类调用构造函数来更改方法的响应方式

例如(这只是为了表达而不是实际代码,但是实际上是在BankAccount类中定义的一种方法)

public void setWithdraw(double withdrawIn)
{
    withdraw = withdrawIn;


    if (withdrawIn is called from savingsAccount && balance < withdrawIn)
    {
        System.out.print("You have insufficient funds");
    }
    else 
    {
        balance = balance - withdrawIn;
        System.out.print("Funds Withdrawn"); 
    }
}

我之所以这样问是因为经过一番研究,我发现您无法覆盖子类中超类的参数,因此让我想知道这是如何完成的. SavingsAccount类将具有其自己的属性,等等,为清楚起见,我将其省略(以防万一,您想知道).

我知道在CheckingAccount中放一个提款方法,在SavingsAccount中放一个提款方法要简单得多,但是由于他们都提款,所以我想看看是否有可能在超级类中使用它.

解决方法:

您可以使用方法的替代:

public class BankAccount {
  public BankAccount(double balanceIn, double withdrawIn) {
    balance = balanceIn;
    setWithdrawn(withdrawIn);
  }

  protected void setWithdrawn(double withdrawIn) {
    // do the base stuff like withdraw = withdrawIn;
  }
}

第二类:

public class SavingsAccount extends BankAccount {
  public BankAccount(double balanceIn, double withdrawIn) {
    super(balanceIn, withdrawIn);
  }

  // overwrite setWithdrawn
  @Override
  protected void setWithdrawn(double withdrawIn) {
    // do the specific stuff like the code of setWithdrawn in your post 
  }
}
上一篇:es6实现继承详解


下一篇:扩展Java中静态方法返回的对象