简体   繁体   中英

Accessors in Java, assistance?

I was just wondering if I could have a little help with accessors, as you can see from my code, I am not supposed to be using int numCols and int numRows as instance variables.

We'll need the accessors getNumOfCols() and getNumOfRows(). We'll need these because the panel shouldn't have its own instance variables for numCols and numRows. If you duplicate this kind of data, you're just asking for problems because it can become inconsistent.

Please can anyone help me create accessors in order to replace my instance variables?

class MineFinderPanel extends JFrame implements MouseListener   // changed
{ 
// numCols and numRows shouldn't get here.  They should be gotten from the model
int numCols;
int numRows;

Accessor methods, known as getters and setters are just used to manipulate fields or variables that should be private and only manipulated by the class that created it. So private fields with public methods.

So you should have a class that creates the model for your Frame.

example of an accessor method. You will have to make another class to implement them:

// private - only available within its class
private int numCols;
private int numRows;

// public methods - ability to access the private fields.
public int getNumCols() {
    return this.numCols;
}

public int getNumRows() {
    return this.numRows;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM