簡體   English   中英

在 Java 中,如何從 class 中的方法訪問 class 變量?

[英]In Java, how do I access class variables from a method within that class?

這感覺像是一個非常基本的問題,我不確定如何更好地表達它,否則我永遠不會發表這篇文章。 我已經嘗試用谷歌搜索將近一個小時了。 這是相關的代碼。

public class Histogram {
public Histogram(int lowerbound, int upperbound) {
    int frequency[] = new int[10];
}

public static void main(String args[]) {
    Histogram histo = new Histogram(0, 5);
    //this section adds a bunch of elements to the histogram, commented out for readability
    System.out.println(histo);
    }

public boolean add(int i) {
    if (i > lowerbound && i < upperbound) {
        ...
    }
}

我無法弄清楚如何訪問傳遞到直方圖 object 中的下限和上限。我正在嘗試使用“添加”方法添加到直方圖的每一層。 它在最后一個塊中,“if (i > lowerbound && i < upperbound)”,我得到了錯誤。

構造器

public class Histogram {
    public Histogram(int lowerbound, int upperbound) {
        int frequency[] = new int[10];
    }
...

具有參數lowerboundupperbound ,但這些參數的范圍僅限於構造函數,因此一旦構造函數退出,這些參數就會超出 scope。(與構造函數中定義的frequency相同。)

而是將字段添加到 class,並將這些字段初始化為 custructor 的一部分:

public class Histogram {
    private int lowerbound;  // define the class field
    private int upperbound;  // define the class field
    public Histogram(int lowerbound, int upperbound) {
        this.lowerbound = lowerbound; // initialize this instance's field value from the parameter that happens to also be named `lowerbound`
        this.upperbound = upperbound; // initialize this instance's field value from the parameter that happens to also be named `upperbound`
        int[] frequency = new int[10]; // when the constructor exits `frequency` goes out of scope and no longer accessible
    }
...

使用與class字段名相同的參數名需要使用this來區分構造函數參數和class字段。 這種替代方法可能有助於澄清:

public class Histogram {
    private int lowerbound;  // define the class field
    private int upperbound;  // define the class field
    public Histogram(int lower, int upper) {
        lowerbound = lower; // initialize this instance's field value
        // this.lowerbound = lower;  Could still use `this`, but it's not needed since the constructor parameter and the class field are different names
        upperbound = upper; // initialize this instance's field value
        // this.upperbound = lower;  Could still use `this`, but it's not needed since the constructor parameter and the class field are different names
        int[] frequency = new int[10]; // when the constructor exits `frequency` goes out of scope and no longer accessible
    }
...

暫無
暫無

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

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