Java:你能在抽象类中调用抽象方法吗?

时间:2018-03-14 05:03:51

标签: java inheritance abstract-methods

如果我调用monthEndUpdate();在我的BankAccount类中,在setBalance行之后,getBalance()得到了它添加了getMonthlyFeesAndInterest()的余额,但在BankAccount类中,getMonthlyFeesAndInterest是抽象的。它会做什么吗?或者它会转到扩展BankAccount的ChequingAccount类并转到它受保护的getMonthlyFeesAndInterest方法吗?

public abstract class BankAccount{
  public void monthEndUpdate() {
    setBalance(getBalance() + getMonthlyFeesAndInterest());
  }
  protected abstract double getMonthlyFeesAndInterest();
}

public class ChequingAccount extends BankAccount{
protected double getMonthlyFeesAndInterest() {
  if(getBalance() >=0)
  {
    return 0.0;
  } else
  {
    return getBalance() * .20;
  }
}

2 个答案:

答案 0 :(得分:0)

由于BankAccount是抽象的,因此您无法直接实例化。相反,您必须实例化ChequingAccount实例:

ChequingAccount chequingAccount = new ChequingAccount();

当您致电chequingAccount.monthEndUpdate()时,系统会调用monthEndUpdate中声明的BankAccount方法(因为您未在ChequingAccount子类中覆盖它)。< / p>

然后,该方法将从您的引用是(getMonthlyFeesAndInterest)实例的类中调用ChequingAccount

编辑:一种思考方式是,除非另有明确规定,否则方法调用会隐含地以this.开头:

public void monthEndUpdate() {
    this.setBalance(this.getBalance() + this.getMonthlyFeesAndInterest());
}

在我们的例子中,this引用了真实类型ChequingAccount的对象,因此JVM首先会查看该方法的实现。如果它找不到实现,它会开始搜索继承链,以找到与方法签名匹配的第一个实现。

答案 1 :(得分:-1)

您的银行帐户类必须是抽象的;具体类中不允许使用抽象方法。

编辑: 在Java中,对象变量具有声明的类型和运行时类型。如果您在BankAccount account = new ChequeingAccount()查找示例,则声明的类型为BankAccount,运行时类型为ChequeingAccount。在运行时,调用的实际方法取决于对象的实际类型,这会导致调用ChequeingAccount的getMonthlyFeesAndInterest()。

有关更多详细信息,请搜索多态性或结帐this link

相关问题