为什么要创建此对象的实例来更改另一个对象的实例变量?

Sam*_*D20 2 java inheritance class

我已经定义了一个bankaccount类,并创建了两个不同的帐户来扩展bankaccount:储蓄帐户和支票帐户.我在下面发布了他们的构造函数:

public class TimeDepositAccount extends SavingsAccount{
    private int numberOfMonths;
    private static final double WITHDRAW_PENALTY = 20;

    TimeDepositAccount(double interestRate, int numberOfMonths){
        super(interestRate);
        this.numberOfMonths = numberOfMonths;
    }
}
Run Code Online (Sandbox Code Playgroud)

和储蓄账户:

public class SavingsAccount extends BankAccount {
    private static double interestRate;

    public SavingsAccount(double interestRate){
        super();
        this.interestRate = interestRate;
    }


}
Run Code Online (Sandbox Code Playgroud)

在我的测试人员中,我创建了savingsaccount,然后是timedeposit帐户:

SavingsAccount momsSavings = new SavingsAccount(5);
TimeDepositAccount collegeFund = new TimeDepositAccount(10, 3);
Run Code Online (Sandbox Code Playgroud)

在通过调试器之后,momsSavings的利率设置为5,就像我指定的那样,但是,当我创建collegeFund时,程序会将momsSavings的利率更改为10,同时创建collegeFund对象.有人能告诉我我的错误在哪里吗?

谢谢.

And*_*mas 6

您已将interestRate声明为静态,因此所有实例中只有一个值.

将其更改为非静态:

 private double interestRate;
Run Code Online (Sandbox Code Playgroud)