Per Effective Java by Joshua Blotch:
There is no way to extend an instantiable class with a new value
component while preserving thecompareTocontract, unless you are
willing to forgo the benefits of object-oriented abstraction
Can you please explain the above with examples and the challenges? Can you also explain what Joshua means by “Value Component” and what other types of components are available.
This frees you to implement whatever
compareTomethod you like on the
second class, while allowing its client to view an instance of the
second class as an instance of the first class when needed.
Can you also explain what Joshua means by second class as an instance of the first class?
Sure. Consider two classes like this – I’ve left out all the getters, setters etc, but hopefully you get the drift:
Ignore whether this is a good example of inheritance – it’s a simple one.
It would be natural for
NamedThingto implement a comparison based on name, in alphabetical order.It would also be natural for
Personto implement a comparison which first compares the name (so stays consistent in that respect) but then also checks for one date of birth being earlier than another.Now imagine this:
What would you want all these results to be? If
Person.compareTowas smart enough to only apply its date processing to instances ofPerson, then you might expectcomparison1andcomparison2to be 0, butcomparison3to be non-zero.Presumably
comparison4would have to be 0, as it’s usingNamedThing.compareTo, which only compares names.Fundamentally, there’s a problem trying to compare instances of different types. It ends up being cleaner to have an external definition of a comparison, which defines what comparison it will use. You could thus have a
Comparator<Person>which only acceptedPersonreferences and used both name and date, and aComparator<NamedThing>which only compared by name. The behaviour would have symmetry and clarity.You’ve taken it out of context. It’s: “view an instance of the second class as an instance of the first class” – e.g.