フォーマットなどを修正してくれてありがとう、ここではまったく新しい
私は最近 Java の学習を始めましたが、ある演習中に 1 つの質問がありました。投稿ルールを見逃していたら申し訳ありません:
ある MyPoint から別の MyPoint までの距離を計算するために、MyPoint another に getter を使用することにしました。
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 が機能する方法はなく、それがインスタンスをプライベートに設定し、ゲッターを使用することの要点だと思いました。
私は何を取りこぼしたか?