繁体   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