并感谢大家修复格式等,全新的
我最近开始学习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无法工作,这就是将实例设置为私有并使用吸气剂。
我错过了什么?
答案 0 :(得分:7)
private
表示只能在MyPoint
内访问这些字段。这并不意味着只能使用{em> MyPoint
的相同实例来访问它们。对于在“其他”实例上运行的方法(尤其是equals
和compareTo
)来访问同一类的其他实例中的私有状态,这是完全合法的。