Troubleshooting Excerpt from Efficient Java on compareTo

This applies to the compareTo contract, which classes can implement.

there is no way to expand an instance of a class with a new value while maintaining the compareTo contract, unless you are willing to give up the benefits of an object-oriented abstraction. The same workaround applies. If you want to add a value component to a class that implements Comparable, do not extend it; write an unrelated class containing an instance of the first class. Then specify "view", the method that returns this instance. This frees you from implementing any compareTo method that you like in the second class, allowing its client to view an instance of the second class as an instance of the first class if necessary.

I read. Why can't I extend an instance of a class with a new value component while maintaining the compareTo contract? . This helped answer one or two questions that I had. But the question below remains unanswered.

1) If I define two classes as unrelated, I am free to implement the compareTo method as I want. This is true. But how do I do two classes with is-a / parent-child relationships. Can someone explain what Joshua called the “look” method?

+4
source share
1 answer

Can anyone explain what Joshua called the “view” method?

I will continue the simple Jon Skeet example from the answer that you linked in your post :

// In Jon code, Person derives from NamedThing class NamedThing { String name; } class Person extends NamedThing { Date dateOfBirth; } 

“Providing a view” rather than “extension” would mean creating a class hierarchy as follows:

 class NamedThing { String name; } class Person { private NamedThing namedThing; // Here is the view method public NamedThing asNamedThing() { return namedThing; } // Here is a convenience method for accessing name directly public String getName() { return namedThing.name; } Date dateOfBirth; } 

This frees you to implement the new compareTo inside Person , because there is no need to remain compatible with the superclass. If you need to view your person as NamedThing , call asNamedThing() to get an idea of ​​the person reduced to an item with a name.

Note that since this is not an is-a relationship, asNamedThing somewhat misleading: you get a named thing inside a person, not a person who is named. This limits the applicability of compareTo : for example, you cannot sort people among other NamedThing s.

+4
source

Source: https://habr.com/ru/post/1492591/


All Articles