Make Java Parent Class Not Part of Interface

(This is a hypothetical question for discussion, I have no real problem).

Say I'm doing an implementation of SortedSet by extending LinkedHashMap :

 class LinkedHashSortedMapThing extends LinkedHashMap implements SortedSet { ... } 

Now programmers who use this class can execute

 LinkedHashMap x = new LinkedHashSortedMapThing(); 

But what if I consider the LinkedHashMap extension LinkedHashMap details and do not want this to be part of the class contract? If people use the line above, I can no longer freely modify this detail without worrying about breaking the existing code. Is there a way to prevent such things besides preferring composition over inheritance (which is not always possible due to private / protected members)?

+4
source share
4 answers

I think the easiest way would be to make a private inner class that extends LinkedHashMap , and LinkedHashSortedMapThing will reference it and indicate all its methods there.

 class LinkedHashSortedMapthing implements SortedSet { private class Foo extends LinkedHashMap { ... } private Foo foo; public void clear() {foo.clear();} public boolean containsValue(Object value) {return foo.containsValue(value);} ... } 
+11
source

If you extend a class, you inherit its public interface, and there is no way to avoid this AFAIK. Composition would be a favorable solution, since in any case you should not depend on the internal elements of LinkedHashMap - this may also change in future versions of the JDK.

Java has no private inheritance, since C ++ do (which is almost equivalent to composition anyway).

+7
source

You can implement SortedSet by aggregating so that the public interface of the class does not include LinkedListHashMap

 class LinkedHashSortedMapThing extends AbstractSet implemenents SortedSet { LinkedListHashMap map; public int size() { return map.size(); } } 
0
source

First, the code must declare a variable using the Set or SortedSet interface. But you can hide the implementation without inheriting from LinkedHashMap. Just implement the interface and delegate it to the LinkedHashMap member.

If you need secure access to LinkedHashMap features, use a private inner class as a member of the delegation.

0
source

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


All Articles