EDIT
I just noticed that you used class equality, not instanceof - this means that reflexivity will be correct. In your example, using super.equals is probably correct if the superclass does not contain an equality definition that contradicts what your subclass requires (e.g. Object ).
The main thing is that the definition of equality should come from only one type (class or interface) in your class hierarchy. If super.equals used in the implementation of this definition, thatβs fine.
END EDIT , source code below
This is almost certainly wrong, because it violates the reflective property of equality.
Say you have a Shape, and it is equal to another Shape if they are of the same type: Square is Square, Circle is Circle, etc. Now you extend this to make ColoredSquare, which adds color checking.
Shape shape1 = new Shape(SQUARE); Shape shape2 = new ColoredShape(SQUARE, RED);
You implement ColoredSquare.equals as super.equals(other) && other.color == this.color , as in your question. But note that shape1.equals(shape2) == true (since shape1 just uses Shape.equals ), but shape2.equals(shape1) == false (since it adds color checking).
The moral of the story is that using this kind of cascading equality is really difficult, if not impossible. Basically, equality should come only from one type within your type hierarchy - be it Object , the type itself, supertype or some interface that defines the contract (for example, in the structure of collections that define equality for Set , List , etc. .).
yshavit
source share