面向对象编程,getter 没有从另一个 class 获取私有变量

Object oriented programming, getter is not getting private variable from another class

该程序应该在 12 个月和 24 个月后计算 2 个帐户的利息。这很好用。我的问题是利率的 getter/setter 不起作用,所以当利率在另一个 class 私有变量中保存为 0.1 时,我无法从主 class 打印它。

public class testAccountIntrest{
    //main method
    public static void main(String[] args) {
        //creating objects
        Account account1 = new Account(500);
        Account account2 = new Account(100);


        //printing data
        System.out.println("");
        System.out.println("The intrest paid on account 1 after 12 months is " + account1.computeIntrest(12));
        System.out.println("");
        System.out.println("The intrest paid on account 1 after 24 months is " + account1.computeIntrest(24));
        System.out.println("");
        System.out.println("");
        System.out.println("The intrest paid on account 2 after 12 months is " + account2.computeIntrest(12));
        System.out.println("");
        System.out.println("The intrest paid on account 2 after 24 months is " + account2.computeIntrest(24));
        System.out.println("");
        System.out.println("The intrest rate is " + getIntrest());


        }//end main method
    }//end main class

class Account {
    //instance variables
    private double balance;
    private double intrestRate = 0.1;

    //constructor
    public Account(double initialBalance) {
        balance = initialBalance;
    }

    //instance methods
    public void withdraw(double amount) {
        balance -= amount;
    }
    public void deposit(double amount) {
        balance += amount;
    }
    public double getBalance() {
        return balance;
    }
    public void setIntrest(double rate) {
        intrestRate = rate;
    }

    public double getIntrest() {
        return intrestRate;
    }

    public int computeIntrest(int n) {
        double intrest = balance*Math.pow((1+intrestRate),(n/12));
        return (int)intrest;
    }
}

getIntrest()是成员方法,所以需要调用

System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
System.out.println("The intrest rate for account 2 is " + account2.getIntrest());

编译器无疑会告诉您,您的 testAccountIntrest class 没有 名为 getInterest() 的方法。因此,仅此一项在 class:

的上下文中无能为力
getInterest()

但是,您的Accountclass确实有那个方法。你在那个范围内有两个 Account objects:

Account account1 = new Account(500);
Account account2 = new Account(100);

因此您可以在这些对象上调用该方法:

account1.getInterest()

或:

account2.getInterest()

基本上,您必须告诉代码您正在调用哪个对象的方法。它无法自行解决。

要从另一个 class 调用方法,您需要另一个 class 的对象。

因此,您需要一个帐户实例来调用 getIntrest。例如:

System.out.println("The intrest rate for account 1 is " + account1.getIntrest());

如果所有帐户的利率都相同,您可以将其设为静态:

private static double intrestRate = 0.1;

public static double getIntrest() {
    return intrestRate;
}

静态字段属于 class,您不需要特定实例即可访问它:

System.out.println("The intrest rate for all accounts is " + Account.getIntrest());