在一个类中,往往有着各种属性。根据属性的访问级别,可以直接调用或者通过方法调用,获取属性值。本章就一句重点,通过对外暴露方法获取属性值,把属性值私有,防止直接调用。
反例
public class Point {
public int x;
public int y;
public Point() {}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(Point src) {
this.x = src.x;
this.y = src.y;
}
}
public class Rect {
public int left;
public int top;
public int right;
public int bottom;
public Rect() {}
public Rect(int left, int top, int right, int bottom) {
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
这两个例子,一般使用都是
Point p = new Point();
p.x = 3;
p.y = 5;
Rect rect = new Rect();
rect.left = 6;
以上两种写法是典型的反例,直接把属性public对外开放,很危险,一不留神哪里改动了,如果不知道的话,程序不会报错,但数据会错误,并且还不好排查原因,好的指导原则就是讲点属性访问权
限,增加对外访问或赋值的方法。修改为
public class Point {
public int x;
public int y;
public Point() {}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(Point src) {
this.x = src.x;
this.y = src.y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
public class Rect {
public int left;
public int top;
public int right;
public int bottom;
public Rect() {}
public Rect(int left, int top, int right, int bottom) {
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public int getLeft() {
return left;
}
public void setLeft(int left) {
this.left = left;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public int getRight() {
return right;
}
public void setRight(int right) {
this.right = right;
}
public int getBottom() {
return bottom;
}
public void setBottom(int bottom) {
this.bottom = bottom;
}
}
访问改为
Point p = new Point();
p.setX(3);
p.setY(5);
Rect rect = new Rect();
rect.setLeft(6);
如果要进行一些校验或约束,可以在方法里开始的时候先对参数进行校验,如果不符合要传入的值,直接抛异常提醒开发者。