Ravi Ravi - 1 month ago 6
Java Question

How to override equals in base and child class

I have one example where I have overriden

equals
methods in both base class and child class.

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;
}

}


While testing I'm getting output :

true
false
false
false


The expected output is :

true
false
false
true


Could anyone tell me what is missing here ?

Answer

As you saw, your code declares to equal Point3D objects (subclass objects) not equal, here d4 and d5. I think this is because of this if statement in Point2D.equals():

    if (Point2D.class != o.getClass()) {
        return false;
    }

o is d5, so its getClass() returns Point3D.class, not the same as Point2D.class. The result returned is also returned from Point3D.equals() and is printed. I think that instead you want

    if (getClass() != o.getClass()) {

Jim Garrison is correct, of course, that you can use a debugger to discover.