sinat_34794545 于 2016.05.10 16:15 提问

Point3D 为什么结果显然不符合事实

package testpoint;

/**
*

• @author Administrator */ public class Point2D { protected double x, y; public Point2D(double x, double y) { this.x = x; this.y = y; } public Point2D() { this(0, 0); } //返回坐标形式的字符串 public String toString() { return "(" + x + ", " + y + ")"; } //判断两个二维点是否重合 public boolean equals(Point2D p) { return x == p.x && y == p.y; } //求到原点距离 public double getDistance() { return Math.sqrt(x * x + y * y); } //根据到原点距离判断点是否为0 public boolean isZero() { return getDistance() == 0; }

}
class Point3D extends Point2D{
protected double z;//新增变量z
public Point3D(double x,double y,double z){//构造方法
super(x,y);//调用父类构造方法,必须写在首行
this.z=z;//初始化
}
public Point3D(){
this(0,0,0);
}
public String toString(){//重写
super.toString();//调被重写的 （x,y,z）
return "(" + x + ", " + y + ","+z+")";//返回
}
public double getDistance(){//重写
super.getDistance();//调父类被重写的 到原点的距离
return Math.sqrt(x*x+y*y+z*z);//返回
}
public boolean equals(Point3D p){//重载（参数变化）重写（参数不变）
return x == p.x && y == p.y&&z==p.z;

`````` }
``````

}
public class TestPoint {

``````/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Point2D p1 = new Point2D(3, 4);//p1=(3,4)
Point2D p2 = new Point2D(0, 0);//p2=(0,0)
Point3D p3 = new Point3D(0, 0, 0);//p3=(0,0,0)
Point3D p4 = new Point3D(0, 0, 0);//p4=(0,0,0)
System.out.println(p1 + "到原点的距离：" + p1.getDistance());
System.out.println(p2 + "是否是0：" + p2.isZero());
System.out.println(p1 + "和" + p2 + "是否重合：" + p1.equals(p2));
System.out.println(p3 + "到原点的距离：" + p3.getDistance());
System.out.println(p4 + "是否是0：" + p4.isZero());
System.out.println(p3 + "和" + p4 + "是否重合：" + p3.equals(p4));
Point2D p23 = new Point2D(0, 0);
Point2D p33 = new Point3D(0, 0, 5);
System.out.println(p23 + "和" + p33 + "是否重合：" + p23.equals(p33));
System.out.println(p33 + "和" + p23 + "是否重合：" + p33.equals(p23));
``````

1个回答

hemethissoulmate   2016.05.10 16:17

// Point2D的equals
public boolean equals(Point2D p) {
if (p instanceof Point3D) {
return false;
}else｛
return x == p.x && y == p.y;
}

// Point3D的equals
public boolean equals(Point2D p) {
if (p instanceof Point3D) {
Point3D p3d = (Point3D)p;
return x == p3d.x && y == p3d.y && z == p3d.z;
}
return false;
}