【发布时间】:2021-01-14 03:12:32
【问题描述】:
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public void setY(int y){
this.y = y;
}
public int getY() {
return y;
}
public void setX(int x){
this.x = x;
}
public int getX() {
return x;
}
我想实现 Sum 方法。但是我似乎找不到在类中使用访问器的好习惯。哪种方法更好?
public int sum(){
return x + y;
}
或者
public int sum(){
return getX() + getY();
}
【问题讨论】:
-
这两种方法都是正确的,但是,您的第二种选择更好。如果实例变量的某些可见性设置不正确或未按照您期望的方式定义,您可能会遇到问题。但是,对于公共 getter,这应该不是问题。