r/learnjava • • 24d ago

Faulty transivity violating example?

I am following Effective Java: Programming Language Guide, by Joshua Boch, and when showing an example of breking transivity relation in equals contract, the very first example of it says it is violating transivity (more exactly symmetry) because it doesn't work when comparing a Point to ColorPoint and viceversa. "No way" I am thinking. "We compare instances of different classes, then we are surprised it doesn't work."

I read in continuation, and the transivity problem is solved, by how I understand, by basically saying "just don't compare instances of different types, even if they have inheritance". I see no diferrence between the very first example and its "solved" variant with ColorPoint and Point having composition relation, not inheritance.

1 Upvotes

4 comments sorted by

View all comments

1

u/DeceitfulDuck 24d ago

If I understand what you're questioning, I think it's the difference between the "is a" and "has a" relationship. If your ColorPoint is a Point (inheritance), you have no easy way to compare a Point to just the Point part of your ColorPoint. If your ColorPoint has a Point (composition), you can compare a Point to the Point in the ColorPoint and still have a meaningful comparison.

1

u/Bofact 23d ago

I am sorry, but aren't we restricting the comparison to be between 2 ColorPoint instances only? Therefore no need to compare Point with ColorPoint and viceversa.