我有一个例子,我在基类和子类中都覆盖了equals
方法。
package com.test;
public class Point2D {
private int x = 0;
private int y = 0;
public Point2D(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return (x + " " + y);
}
@Override
public boolean equals(Object o) {
if (Point2D.class != o.getClass()) {
return false;
}
if ((o instanceof Point2D)) {
if ((((Point2D) o).x == this.x) && (((Point2D) o).y == this.y)) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
return x + y;
}
}
class TestPoint2D {
public static void main(String args[]) {
Point2D d2 = new Point2D(2, 4);
Point2D d3 = new Point2D(2, 4);
Point3D d4 = new Point3D(2, 4, 5);
Point3D d5 = new Point3D(2, 4, 5);
System.out.println(d2.equals(d3));
System.out.println(d3.equals(d5));
System.out.println(d5.equals(d3));
System.out.println(d4.equals(d5));
}
}
class Point3D extends Point2D {
private int z = 0;
public Point3D(int x, int y, int z) {
super(x, y);
this.z = z;
}
@Override
public boolean equals(Object o) {
if ((o instanceof Point3D)) {
if ((((Point3D) o).z == this.z)) {
Point2D obj = (Point2D) o;
return super.equals(obj);
}
}
return false;
}
@Override
public int hashCode() {
return super.hashCode() + z;
}
}
在测试时我得到了输出:
true
false
false
false
预期输出为:
true
false
false
true
有人能告诉我这里缺少什么吗?
答案 0 :(得分:0)
如您所见,您的代码声明两个相等的Point3D
对象(子类对象)不相等,此处为d4
和d5
。我认为这是因为Point2D.equals()
中的if语句:
if (Point2D.class != o.getClass()) {
return false;
}
o
为d5
,因此其getClass()
会返回Point3D.class
,与Point2D.class
不同。返回的结果也从Point3D.equals()
返回并打印出来。我认为相反,你想要
if (getClass() != o.getClass()) {
当然,Jim Garrison是正确的,您可以使用调试器来发现。