【发布时间】:2013-08-28 16:02:15
【问题描述】:
感谢大家修复格式等,这里是全新的
我最近开始学习java,在一次练习中遇到了一个问题,如果我错过了发布规则,请见谅:
为了计算一个 MyPoint 到另一个 MyPoint 的距离,我决定为 MyPoint another 使用 getter,因为 another 的 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;
}
}
我认为由于 another 是一个 MyPoint 类并且实例 x 和 y 是私有的,因此 .x 和 .y 无法工作,这就是将实例设置为私有并使用吸气剂。
我错过了什么?
【问题讨论】: