package q5; class Point2D { int x; int y; public Point2D(int x, int y) { this.x = x; this.y = y; } public void offset(int a, int b) { this.x += a; this.y += b; } public double distance(Point2D p) { double dx = this.x - p.x; double dy = this.y - p.y; return Math.sqrt(dx*dx + dy*dy); } } class Point3D extends Point2D { int z; public Point3D(int x, int y, int z) { super(x, y); this.z = z; } public Point3D(Point2D p, int z) { super(p.x, p.y); this.z = z; } public void offset(int a, int b, int c) { super.offset(a, b); this.z += c; } public double distance(Point3D p) { double dx = this.x - p.x; double dy = this.y - p.y; double dz = this.z - p.z; return Math.sqrt(dx*dx + dy*dy + dz*dz); } } // test code public class Main { public static void main(String[] args) { Point2D p2d1 = new Point2D(0, 0); Point2D p2d2 = new Point2D(3, 4); double distance2D = p2d1.distance(p2d2); System.out.println("The distance between p2d1 and p2d2 is " + distance2D); Point3D p3d1 = new Point3D(0, 0, 0); Point3D p3d2 = new Point3D(p2d2, 5); double distance3D = p3d1.distance(p3d2); System.out.println("The distance between p3d1 and p3d2 is " + distance3D); } }请为以上代码添加注释
时间: 2023-06-08 20:03:38 浏览: 353
// 定义一个二维坐标类
package q5;
class Point2D {
int x; // 坐标 x
int y; // 坐标 y
// 构造函数
public Point2D(int x, int y) {
this.x = x;
this.y = y;
}
// 偏移坐标
public void offset(int a, int b) {
this.x = a;
this.y = b;
}
// 计算两点之间的距离
public double distance(Point2D p) {
double dx = this.x - p.x;
double dy = this.y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
// 定义一个三维坐标类,继承于二维坐标类
class Point3D extends Point2D {
int z; // 坐标 z
// 构造函数
public Point3D(int x, int y, int z) {
super(x, y); // 调用父类构造函数初始化 x, y
this.z = z;
}
// 构造函数,传入二维坐标对象和 z 坐标值
public Point3D(Point2D p, int z) {
super(p.x, p.y); // 调用父类构造函数初始化 x, y
this.z = z;
}
// 偏移坐标
public void offset(int a, int b, int c) {
super.offset(a, b); // 调用父类的 offset 方法
this.z = c;
}
// 计算两点之间的距离
public double distance(Point3D p) {
double dx = this.x - p.x;
double dy = this.y - p.y;
double dz = this.z - p.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
Point2D p2d1 = new Point2D(0, 0);
Point2D p2d2 = new Point2D(3, 4);
double distance2D = p2d1.distance(p2d2);
System.out.println("The distance between p2d1 and p2d2 is " + distance2D);
Point3D p3d1 = new Point3D(0, 0, 0);
Point3D p3d2 = new Point3D(p2d2, 5);
double distance3D = p3d1.distance(p3d2);
System.out.println("The distance between p3d1 and p3d2 is " + distance3D);
}
}
阅读全文