8. 创建一个 Point类, 包含坐标x、y。然后创建一个 MyPoint类, 定义两个读写变量 start和 end, 数据类型为 Point。MyPoint()方法: 计算 start和 end之间的距离并输出 start 和 end 坐标以及距离信息。
时间: 2024-10-17 12:07:50 浏览: 66
首先,我们来创建一个名为`Point`的基本类,它表示二维空间中的一个点,包含两个属性`x`和`y`。
```java
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// getters and setters for x and y
public double getX() { return x; }
public void setX(double newX) { x = newX; }
public double getY() { return y; }
public void setY(double newY) { y = newY; }
}
```
接着,我们将创建`MyPoint`类,它继承自`Point`,并在其中定义了两个`start`和`end`属性,也是`Point`类型的:
```java
public class MyPoint extends Point {
private Point start;
private Point end;
public MyPoint(Point start, Point end) {
super(start.getX(), start.getY());
this.start = start;
this.end = end;
}
// getter and setter methods for start and end
public Point getStart() { return start; }
public void setStart(Point newStart) { start = newStart; }
public Point getEnd() { return end; }
public void setEnd(Point newEnd) { end = newEnd; }
@Override
public String toString() {
double distance = calculateDistance();
return "Start coordinates: (" + start.getX() + ", " + start.getY() + "), End coordinates: (" + end.getX() + ", " + end.getY() + "), Distance: " + distance + " units";
}
private double calculateDistance() {
double dx = end.getX() - start.getX();
double dy = end.getY() - start.getY();
return Math.sqrt(dx * dx + dy * dy);
}
}
```
在这个`MyPoint`类中,`calculateDistance()`方法计算了两个点之间的欧氏距离,并在`toString()`方法中返回了起始点、终点的坐标以及它们之间的距离。
阅读全文