利用java的程序给point类添加以下几个求两点间距的多态方法
时间: 2023-06-11 07:06:15 浏览: 71
可以在Point类中添加以下多态方法来计算两点之间的距离:
```java
public class Point {
private double x;
private double y;
// 构造方法
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// 获取x坐标
public double getX() {
return x;
}
// 获取y坐标
public double getY() {
return y;
}
// 计算两点之间的欧几里得距离
public static double distance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
// 计算两点之间的曼哈顿距离
public static double distance(Point p1, Point p2, String distanceType) {
if (distanceType.equals("manhattan")) {
double dx = Math.abs(p1.x - p2.x);
double dy = Math.abs(p1.y - p2.y);
return dx + dy;
} else {
return distance(p1, p2);
}
}
}
```
其中,`distance` 方法计算两点之间的欧几里得距离,`distance` 方法还可以根据传入的 `distanceType` 参数来计算两点之间的曼哈顿距离。如果 `distanceType` 为 `manhattan`,则计算曼哈顿距离;否则,计算欧几里得距离。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)