创建一个Point类,包括坐标x,y.然后创建一个MyPoint类,定一两个读写变量start和end,数据类型为Point。MyPoint()方法:计算start和end之间的距离并输出start和end坐标以及距离信息
时间: 2024-11-25 11:31:04 浏览: 35
首先,我们可以创建一个名为`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 the coordinates
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;
}
}
```
接着,我们创建一个名为`MyPoint`的派生类,它继承自`Point`并添加了开始点(start)和结束点(end)及其相关方法:
```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 for start and end points
public Point getStart() {
return start;
}
public void setStart(Point start) {
this.start = start;
}
public Point getEnd() {
return end;
}
public void setEnd(Point end) {
this.end = end;
}
// Method to calculate distance between start and end points
public double calculateDistance() {
double distance = Math.sqrt(Math.pow((end.getX() - start.getX()), 2)
+ Math.pow((end.getY() - start.getY()), 2));
System.out.println("Start point: (" + start.getX() + ", " + start.getY()
+ ")");
System.out.println("End point: (" + end.getX() + ", " + end.getY() + ")");
System.out.println("Distance: " + distance);
return distance;
}
}
```
现在,你可以实例化`MyPoint`类,并计算两点之间的距离:
```java
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
MyPoint myPoint = new MyPoint(p1, p2);
myPoint.calculateDistance();
}
```
阅读全文