簡體   English   中英

面向對象的編程,getter不會從另一個類獲取私有變量

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

該程序應在12和24個月后計算2個帳戶的利息。 這很好。 我的問題是利率的getter / setter方法不起作用,因此,當利率在另一個類的私有變量中保存為0.1時,無法從主類中打印出來。

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;
    }
}

由於編譯器無疑是在告訴你,你的testAccountIntrest沒有一個叫方法getInterest() 因此,僅此一個類就無法在該類的上下文中做任何事情:

getInterest()

但是,您的Account確實具有該方法。 在該范圍內,您有兩個Account 對象

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

因此,您可以在那些對象上調用該方法:

account1.getInterest()

要么:

account2.getInterest()

基本上,您必須告訴代碼正在調用該方法的對象。 它無法自行解決。

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());

要從另一個類調用方法,您需要另一個類的對象。

因此,您需要一個account實例來調用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;
}

靜態字段屬於該類,您不需要特定的實例即可訪問它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM