编程题: 2、创建一个Point 类,包含坐标x、y。然后创建一个MyPoint类,定义两个读写变量start和end,数据类型为Point。MyPoint()方法:计算start和end之间的距离并输出
时间: 2024-09-10 10:07:11 浏览: 183
首先,我们需要创建一个基础的`Point`类,该类将包含坐标`x`和`y`作为私有成员变量。接着,我们将创建一个名为`MyPoint`的类,该类将包含两个`Point`类型的读写变量`start`和`end`。`MyPoint`类中还需要一个构造方法来初始化`start`和`end`,以及一个计算并输出这两个点之间距离的方法。距离可以通过计算两点间的欧几里得距离得出。
以下是一个简单的实现示例:
```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 x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
public class MyPoint {
private Point start;
private Point end;
public MyPoint(Point start, Point end) {
this.start = start;
this.end = end;
}
// Method to calculate and output the distance between start and end
public void printDistance() {
double distance = Math.sqrt(Math.pow(end.getX() - start.getX(), 2) + Math.pow(end.getY() - start.getY(), 2));
System.out.println("The distance between start and end points is: " + distance);
}
// Getters and setters for start and end
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;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Point start = new Point(1, 1);
Point end = new Point(4, 5);
MyPoint myPoint = new MyPoint(start, end);
myPoint.printDistance();
}
}
```
在这个例子中,`Point`类是使用构造方法初始化的,同时提供了`x`和`y`坐标的getter和setter方法。`MyPoint`类中包含了两个`Point`对象作为成员变量,并且在构造方法中进行初始化。`printDistance`方法用于计算两点之间的距离并打印结果。
阅读全文