本文實作一個 Point 類別,用於表示三維空間中的點,包含座標封裝、設值方法、距原點距離平方計算與主程式驗證。
public class Point {
private double x;
private double y;
private double z;
public double getX() { return x; }
public void setX(double x) { this.x = x; }
public double getY() { return y; }
public void setY(double y) { this.y = y; }
public double getZ() { return z; }
public void setZ(double z) { this.z = z; }
public Point(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public void getJuLi() {
System.out.println("點(" + x + "," + y + "," + z + ")距離原點的平方=" + (x * x + y * y + z * z));
}
public static void main(String[] args) {
Point p = new Point(5, 3, 8);
p.setY(-2.5);
p.getJuLi(); // 輸出:點(5.0,-2.5,8.0)距離原點的平方=95.25
Point p1 = new Point(-1, 3, 5);
p1.getJuLi(); // 輸出:點(-1.0,3.0,5.0)距離原點的平方=35.0
}
}
p(5, -2.5, 8):5² + (-2.5)² + 8² = 25 + 6.25 + 64 = 95.25p1(-1, 3, 5):(-1)² + 3² + 5² = 1 + 9 + 25 = 35程式碼展示了封裝性、建構子多載、Getter/Setter 模式與簡單幾何運算的 Java 實作。
