Java面向对象应用:设计一个类Point2D,用来表示二维平面中某个点计算点的距离

设计一个类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));
	}
}

 

希望对你有所帮助,欢迎订阅我的博客!

  • 15
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值