The constructor
public class Histogram {
public Histogram(int lowerbound, int upperbound) {
int frequency[] = new int[10];
}
...
has parameters lowerbound
and upperbound
, but those parameters are scoped to the constructor, so once the constructor exits those parameters are out of scope. (Same for frequency
defined within the constructor.)
Instead add fields to the class, and initialize those fields as part of the 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
}
...
Using the same parameter name as the class field name requires the use of this
to distinguish between the constructor parameter and the class field. This alternative might help to clarify:
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
}
...