Java – why can’t I extend instantiatable classes with new value components while retaining the CompareTo contract?
Each valid Java for Joshua Bloch:
Could you please explain the above problems through examples and challenges? Can you explain what Joshua means to "value components" and whether other types of components are available
Can you explain what Joshua meant when second class was the first class?
Solution
of course. Consider these two classes – I've omitted all getters, installers, etc., but I want you to get drift:
class NamedThing { String name; } class Person extends NamedThing { Date dateOfBirth; }
Ignore whether this is a good inheritance example - this is a simple example
It's natural for namedthing to implement name - based comparisons in alphabetical order
It is also natural for people to compare names first (so consistent in this regard), and then check that one birth date is earlier than another
Now imagine:
NamedThing person1 = new Person("Jon",date1); NamedThing person2 = new Person("Jon",date2); NamedThing thing = new NamedThing("Jon"); int comparison1 = person1.compareTo(thing); int comparison2 = person2.compareTo(thing); int comparison3 = person1.compareTo(person2); int comparison4 = thing.compareTo(person1);
What do you want all these results to be? If person CompareTo is smart enough to only apply its date processing to instances of person, so you may want comparison1 and comparison2 to be 0, but compare3 to be non-zero
Presumably compare4 must be 0 because it uses namedthing CompareTo, which compares only names
Fundamentally, trying to compare different types of instances is problematic It eventually becomes clearer, with an external definition of comparison, which defines the comparison it will use Therefore, you can have a comparator < person > that accepts only person references and uses names and dates, and comparator < namedthing > compares only by name The behavior will have symmetry and clarity
You are out of context It is: "treat instances of the second class as instances of the first class" – for example
// First class = Animal // Second class = Zebra Animal person = new Zebra();