并感谢大家修复格式等,这里是全新的
我最近开始学习 java,在一次练习中出现了一个问题,如果我错过了发布规则,请见谅:
为了计算从一个 MyPoint 到另一个 MyPoint 的距离,我决定对另一个 MyPoint 使用 getter,因为另一个的x 和 y应该是私有的,不能用于点操作(another.x another.y);
public class MyPoint {
private int x;
private int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(MyPoint another) {
int xDiff = this.x - another.getX(); //getter
int yDiff = this.y - another.getY(); // getter
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint a = new MyPoint(3,0);
MyPoint b = new MyPoint(0,4);
System.out.println(a.distance(b)); // this works fine;
}
}
但是,如果我返回代码并将 another.getX() 更改为 another.x,代码仍然有效。和 y 一样。
public class MyPoint {
private int x;
private int y;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(MyPoint another) {
int xDiff = this.x - another.x; //no getter
int yDiff = this.y - another.y; //no getter
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint a = new MyPoint(3,0);
MyPoint b = new MyPoint(0,4);
System.out.println(a.distance(b)); // this still works fine;
}
}
我认为由于另一个是 MyPoint 类并且实例 x 和 y 是私有的,因此 .x 和 .y 无法工作,这就是将实例设置为私有并使用 getter 的全部意义所在。
我错过了什么?