OK, here we have an example from Effective Java (I have the second edition of 2008). An example is in ITEM 8: OBEY THE GENERAL CONTRACT WHEN OVERRIDING EQUALS , starting on page 37 (I write this if you want to check).
class ColoredPoint extends Point{} and there are 2 attepts in the demo why instanceof is BAD. First attempt was
// Broken - violates symmetry! @Override public boolean equals(Object o) { if (!(o instanceof ColorPoint)) return false; return super.equals(o) && ((ColorPoint) o).color == color;
}
and the second was
// Broken - violates transitivity! @Override public boolean equals(Object o) { if (!(o instanceof Point)) return false; // If o is a normal Point, do a color-blind comparison if (!(o instanceof ColorPoint)) return o.equals(this); // o is a ColorPoint; do a full comparison return super.equals(o) && ((ColorPoint)o).color == color;
}
First of all, a second IF will never be achieved. If the "o" is not a point that is a superclass for ColorPoint, how can this happen, the point should not be ColorPoint ??????
So, the second attempt is wrong from the very beginning! Where the only chance for a TRUE comparison is super.equals(o) && ((ColorPoint)o).color == color; what is not enough! the solution here would be as follows:
if (super.equals(o)) return true; if (!(o instanceof ColorPoint)) if ((o instanceof Point)) return this.equals(o); else return false; return (color ==((ColorPoint)o).color && this.equals(o));
obj.getClass () is used for very specific equals (), but your implementations depend on your area. How do you determine if two objects are equal or not? Deploy it and it will work accordingly.
source share