如何让子类继承一个没有Java中值的变量



我有一个BankAccount摘要类,该类别有两个子类 - SavingsAccount和CreditAccount。这两个子类共享一组具有不同值的变量,例如SavingsAccount的1%利息率,CreditAccount的0.5%。由于它们还共享了使用兴趣率变量的几种方法,因此我希望它们继承变量和使用它的方法(而不是两次编写这些方法)。

我可以以某种方式让子类继承兴趣率变量,并在子类中赋予我想要的值,或者还有其他方法可以解决此问题?

执行此操作的两种方法;

  1. 给您的基类构造函数(不用担心,它仍然是抽象的),它初始化了实例变量,并为变量提供受保护的访问者。

  2. 使实例变量受到保护。

示例:

abstract class BankAccount {
    private BigDecimal interestRate;
    protected BankAccount(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
    protected BigDecimal getInterestRate() {
        return this.interestRate;
    }
}
class SavingsAccount extends BankAccount {
    public SavingsAccount(BigDecimal interestRate) {
        super(interestRate);
    }
    // ...code in methods can use `this.getInterestRate()`...
}

或(但是I 不推荐它):

abstract class BankAccount {
    protected BigDecimal interestRate;
    protected BankAccount(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}
class SavingsAccount extends BankAccount {
    public SavingsAccount(BigDecimal interestRate) {
        super(interestRate);
    }
    // ...code in methods can use `this.interestRate` directly...
}

最新更新