设计一个类Point2D,用来表示二维平面中某个点:
1> 属性
* double x
* double y
2> 方法
* 属性相应的set和get方法
* 设计一个对象方法同时设置x和y
* 设计一个对象方法计算跟其他点的距离
* 设计一个类方法计算两个点之间的距离
分别创建两个类文件:
其中Point2D.java封装:
/*
* 用来表示二维平面中某个点
*/
public class Point2D {
private double x;
private double y;
// 对象方法同时设置x和y
public void setXY(double x, double y) {
this.x = x;
this.y = y;
}
// 对象方法计算跟其他点的距离
public double pointDistance(Point2D other) {
return Math.sqrt((Math.pow((this.x - other.x), 2) + Math.pow((this.y - other.y), 2)));
}
// 类方法计算两个点之间的距离
public static double pointDistance(Point2D point1, Point2D point2) {
return Math.sqrt((Math.pow((point1.x - point2.x), 2) + Math.pow((point1.y - point2.y), 2)));
}
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;
}
}
Point2DTest.java测试:
public class Point2DTest {
public static void main(String[] args) {
Point2D point1 = new Point2D();
Point2D point2 = new Point2D();
Point2D other = new Point2D();
point1.setXY(1, 1);
point2.setXY(1, 0);
other.setXY(2, 2);
System.out.println("与其他点的距离为:" + point1.pointDistance(other));
System.out.println("两点的距离为:" + Point2D.pointDistance(point1, point2));
}
}
希望对你有所帮助,欢迎订阅我的博客!