(The MyPoint class) Design a class named MyPoint to represent a point with x- and y-coordinates. The class contains: ■ The data fields x and y that represent the coordinates with getter methods. ■ A no-arg constructor that creates a point (0, 0). ■ A constructor that constructs a point with specified coordinates. ■ A method named distance that returns the distance from this point to a specified point of the MyPoint type. ■ A method named distance that returns the distance from this point to another point with specified x- and y-coordinates. Draw the UML diagram for the class and then implement the class. Write a test program that creates the two points (0, 0) and (10, 30.5) and displays the distance between them.
时间: 2024-02-20 15:58:50 浏览: 18
以下是 MyPoint 类的 UML 图:
```
_________________________
| MyPoint |
|-----------------------|
| -x: double |
| -y: double |
|-----------------------|
| +MyPoint() |
| +MyPoint(x: double, |
| y: double) |
| +getX(): double |
| +getY(): double |
| +distance(point: |
| MyPoint): |
| double |
| +distance(x2: double, |
| y2: double) |
| double |
-------------------------
```
以下是 MyPoint 类的实现:
```java
public class MyPoint {
private double x;
private double y;
public MyPoint() {
this(0, 0);
}
public MyPoint(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double distance(MyPoint point) {
return distance(point.getX(), point.getY());
}
public double distance(double x2, double y2) {
return Math.sqrt(Math.pow(x2 - x, 2) + Math.pow(y2 - y, 2));
}
}
```
以下是测试程序:
```java
public class TestMyPoint {
public static void main(String[] args) {
MyPoint p1 = new MyPoint();
MyPoint p2 = new MyPoint(10, 30.5);
System.out.println("Distance between (" + p1.getX() + ", " + p1.getY() + ") and (" +
p2.getX() + ", " + p2.getY() + ") is " + p1.distance(p2));
}
}
```
输出:
```
Distance between (0.0, 0.0) and (10.0, 30.5) is 32.09750769140807
```