如何更新在不同类中声明的变量?

时间:2015-04-20 15:13:16

标签: java variables

您好我正在做这项功课,它几乎已经完成,但有一件事不能正常工作。我创建了这两个类“SavingAccount”和“TimeAccount”,“Account”的子类,它们有不同类型的兴趣计算,包括帐户上次更新的当前时间和时间。我有一个时间变量,它被建模为几个月,并在我的Test类中声明为零。每当我存款,取款或转账时,都应更新账户lastTimeUpdated变量。但它不起作用。 以下是我在帐户类

中的存款和取款方法
protected int currentTime = Test.month;
protected int timeUpdated;    

public abstract double getBalance();

public void withdraw(double amount){
    if(amount <= balance){
        balance = this.getBalance();
        balance -= amount;
        timeUpdated = currentTime;
    }
    else
        System.out.println("Not enough funds...");
}

public void deposit(double amount){
    balance = this.getBalance();
    balance += amount;
    timeUpdated = currentTime;
}

我为子类重写了getBalance()方法; SavingAccount:

    @Override
    public double getBalance() {
        double a = (1+term*interestRate/12);
        double b = (currentTime-timeUpdated)/term;
        balance = balance*Math.pow(a,b);
        return balance;
    }

TimeAccount:

    public double getBalance(){
        double a = 1+interestRate/12;
        double b = currentTime-timeUpdated;
        balance = balance*Math.pow(a,b);
        return balance;
    }

在我的测试类中,有一个月变量,click()方法增加了一个月。我使用过它,但时间没有在我的帐户类中更新。

public static int month = 0;

static void click(){
    month++;
    System.out.println("Current month is " + month);
}

static void click(int x){
    month += x;
    System.out.println("Current month is " + month);
}

所以我的问题是我无法更新帐户中的时间,这就是为什么兴趣无效并且余额保持不变。提前谢谢。

编辑:我的问题标记为“重复”。但我在其他问题中找不到答案。因此month在我的测试类中不应该是static吗?那我怎么能在我的main方法中使用click()方法呢?

0 个答案:

没有答案