Solution to 5235: Equality between points
See code at solutions/code/tutorialquestions/question5235
With a plain old Point class, before overriding equals, you should find that
comparing identical points represented by distinct objects with equals yields false.
DemoWithoutEquals.java gives an example of this.
Implementing equals for points is straightforward using the recipe given in the lectures.
See pointequality/Point.java for the implementation.
The main method in pointequality/PointEqualityDemo.java shows that having overridden
equals for Point, we now have a problem with ColouredPoint. Declaring:
ColouredPoint cp = new ColouredPoint(1.2, 2.3, 3.4, Colour.Red);
ColouredPoint cq = new ColouredPoint(1.2, 2.3, 3.4, Colour.Blue);
we find that cp.equals(cq) holds, even though these points have different colours.
To fix this, you were asked to override equals in ColouredPoint. Look at
colouredpointequality/ColouredPoint.java to see how this can be done. Most interesting
is the last line of the equals method:
return super.equals(thatPoint) && colour == thatPoint.colour;
Notice that super is used to check first whether the coloured points are equal when
regarded as plain old points. Additionally, for them to be regarded as equal as coloured points,
their colours must match.
Finally, the asymmetry of equals is illustrated in colouredpointequality/PointEqualityDemo.java:
the last thing main prints is:
Points p = (1.2, 2.3, 3.4) and cp = ((1.2, 2.3, 3.4), Red) are equal
Points cp = ((1.2, 2.3, 3.4), Red) and p = (1.2, 2.3, 3.4) are not equal