syg*_*ede 2 java oop getter private
并感谢每个人修复格式等,这里全新
我最近开始学习java,在一次练习中发生了一个问题,抱歉,如果我错过了发布规则:
从一个MyPoint到另一个Mypoint计算距离,我决定使用用于MyPoint吸气另一个因为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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我回到代码并将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;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为,因为另一个是MyPoint类,而实例x和y是私有的,所以.x和.y无法工作,这就是设置私有实例并使用getter的重点.
我错过了什么?
private表示只能从内部访问字段MyPoint.这并不意味着他们只能从与访问同一个实例的MyPoint.这对于那些在"其他"的情况下,尤其是操作方法完全合法的equals,并compareTo在同一类的其他实例来访问私有状态.
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |