java中方法和构造方法的小练习

定义一个点Ponit类,用来表示三维空间中的点

要求如下:

1.可以生成特定坐标的点对象

2.提供设置坐标的方法

3.计算该点与原点距离的平方的方法

TestPoint.java

/*
	定义一个点Ponit,用来表示三维空间中的点,要求如下:
	1.可以生成特定坐标的点对象
	2.提供设置坐标的方法
	3.计算该点与原点距离的平方的方法
*/
class Point {
	double x, y, z;
	//构造方法,生成特定的点对象
	Point(double x, double y, double z){
		this.x = x;
		this.y = y;
		this.z = z;	
	}	
	//设置坐标的方法
	void setX(double x) {
		this.x = x;	
	}
	void setY(double y) {
		this.y = y;	
	}
	void setZ(double z) {
		this.z = z;	
	}
	//计算距离的平方
	double getDistance(Point p) {
		return (x - p.x)*(x - p.x) + (y - p.y)*(y - p.y) + (z - p.z)*(z - p.z);
	}
}

public class TestPoint {
	public static void main(String[] args) {
			Point p = new Point(1.0,2.0,3.0);
			Point p1 = new Point(0.0,0.0,0.0);
			System.out.println(p.getDistance(p1));//计算点p到原点的距离的平方,结果为14
			
			p.setX(5.0);//重新设置点p的x坐标
			System.out.println(p.getDistance(new Point(1.0,1.0,1.0)));//计算点p到(1.0,1.0,1.0)的距离的平方,结果为21
			
	}
}

猜你喜欢

转载自mfcfine.iteye.com/blog/2380859