[Effective Java] Item 14: Use access methods instead of public fields in public classes

In normal development, you will also define certain classes, which have no effect, but only focus on some instance fields. Such as:

class Point {
    public float x;
    public float y;
}

Since the class is designed in this way, it can be accessed directly through the object, which is much simpler. But this is not in line with the object-oriented idea. xWhat should I do if the calculation method is changed?

So preferably we provide access methods for instance fields like:

class Point {
    private float x;
    private float y;

    public float getX() {return x;}

    public float getY() {return y;}

    public void setX(float x) {this.x = x;}
    public void setY(float y) {this.y = y;}
}

If x( y) calculates the modification, we can modify it through the getXmethod, and it will not be passive like the public domain.

For package privateor inline classes, although it will not affect the user-facing API, I still recommend the access method. After all, the generated access methods can be automatically generated now, and it will not be too troublesome.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325950040&siteId=291194637