10.4 (The MyPoint class) Design a class named MyPoint to represent a point with
x- and y-coordinates. The class contains:
■ The data fields x and y that represent the coordinates with getter
methods.
■ A no-arg constructor that creates a point (0, 0).
■ A constructor that constructs a point with specified coordinates.
■ A method named distance that returns the distance from this point to a
specified point of the MyPoint type.
■ A method named distance that returns the distance from this point to
another point with specified x- and y-coordinates.
Draw the UML diagram for the class and then implement the class. Write a
test program that creates the two points (0, 0) and (10, 30.5) and displays the
distance between them.
10.4(Mypoint类)设计一个名为MyPoint的类来表示一个具有x和y坐标的点。类包含:
■ 数据字段x和y表示带有getter方法的坐标
■ 创建点(0,0)的无参数构造函数.
■ 构造具有指定坐标的点构造函数
■ 名为distance的方法,它返回这个点到MyPoint指定点的距离
■ 名为distance的方法,它返回这个点到另一个特定点的特定坐标x,y的距离
绘制类的UML图,但后实现类.编写一个测试程序,创建两个点(0,0)和(10,30.5),并显示它们之间的距离
代码如下:
public class Unite10Test4
{
public static void main(String[] args)
{
MyPoint m1=new MyPoint(0,0);
MyPoint m2=new MyPoint(10,30.5);
double x=m1.getX();
double y=m1.getY();
System.out.println("它们之间的距离为: "+m2.distance(x, y));
}
}
class MyPoint
{
private double x;
private double y;
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;
}
//属性
public MyPoint()
{
}
public MyPoint(double x,double y)
{
this.x=x;
this.y=y;
}
public double distance()
{
return Math.sqrt((this.x*this.x)-(x*x)+(this.y*this.y)-(y*y));
}
public double distance(double x,double y)
{
return Math.sqrt((this.x*this.x)-(x*x)+(this.y*this.y)-(y*y));
}
}
结果如下: