Java 编写Point类,有两个属性x、y,一个方法distance(Point p1,Point p2),计算两者之间的距离。 说明:注意方法参数为引用类型
时间: 2024-10-23 21:13:38 浏览: 45
在Java中,你可以按照以下步骤来创建一个名为`Point`的类,它有两个属性`x`和`y`,以及一个计算两点之间距离的方法`distance`:
1. 定义`Point`类[^1]:
```java
public class Point {
private double x;
private double y;
// 构造器
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// 计算两点间距离的方法
public double distance(Point p2) {
double deltaX = p2.getX() - this.x;
double deltaY = p2.getY() - this.y;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY); // 使用毕达哥拉斯定理
}
// 获取x和y属性的方法
public double getX() {
return x;
}
public double getY() {
return y;
}
}
```
2. 创建`PointDemo`类以测试`distance`方法[^2]:
```java
public class PointDemo {
public static void main(String[] args) {
// 实例化点对象
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
// 调用distance方法并打印结果
double distance = p1.distance(p2);
System.out.println("Distance between points p1 and p2: " + distance);
}
}
```
在这个例子中,我们首先定义了一个`Point`类,其中包含`x`和`y`属性以及`distance`方法。然后在`main`方法中,我们创建了两个`Point`对象`p1`和`p2`,并将它们的距离计算出来。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)