Valid Java, inclutivejava
Inheritance is one of the methods for implementing code reuse, But improper use may cause many problems.
Inheritance destroys encapsulation, and it is dangerous to inherit a specific class at the cross-package access level.
That is, subclass depends on the implementation details of the parent class.
If the implementation details of the parent class change, the Child class may be damaged.
For example, the HashSet extension records the number of times that elements have been added since the creation of the HashSet instance.
HashSet has two ways to add elements: add (E) and addAll (Collection <? Extends E> c ).
Overwrite the two methods and record the number of times before the add operation is executed:
public class InstrumentedHashSet<E> extends HashSet<E> { // The number of attempted element insertions private int addCount = 0; public InstrumentedHashSet() { } public InstrumentedHashSet(int initCap, float loadFactor) { super(initCap, loadFactor); } @Override public boolean add(E e) { addCount++; return super.add(e); } @Override public boolean addAll(Collection<? extends E> c) { addCount += c.size(); return super.addAll(c); } public int getAddCount() { return addCount; }}
To test the function, add three elements using the addAll method:
public static void main(String[] args) { InstrumentedHashSet<String> s = new InstrumentedHashSet<String>(); s.addAll(Arrays.asList("Snap", "Crackle", "Pop")); System.out.println(s.getAddCount());}
Result: wKioL1PLrWjBf_fsAADIJ3WV64w978.jpg
The reason for this is simple.
See add (E) and addAll (Collection <? Extends E> c), add (E) has only one throw new UnsupportedOperationException ();
And addAll (Collection <? Extends E> c) the document notes include the following:
* <p>Note that this implementation will throw an* <tt>UnsupportedOperationException</tt> unless <tt>add</tt> is* overridden (assuming the specified collection is non-empty).
The solution to this problem is simple. You only need to remove the covered addAll method.
However, the root problem cannot be solved, that is, the addAll method of the HashSet cannot be changed in future releases.
That is, the subclass implementation depends on the parent class implementation. When the parent class changes, the subclass is damaged.
Maybe we can override the parent class method to implement it again. Although the problem is solved, it is meaningless to make effort and effort.
In addition, adding or removing methods to the parent class will also affect the subclass.
For example, a subclass extends a collection class and covers all methods for adding elements. Before adding elements, the subclass checks the elements so that all elements meet a certain condition.
In a later version, if the parent class adds a new method for adding elements, and the subclass does not overwrite the method, illegal elements will be added to the set.
This may also happen.
Even if the implementation of the parent class is correct, the constraints of the parent class can be damaged due to improper implementation of the Child class.
For example, the parent class just adds a method with the same signature and return type as the subclass.
To cope with these situations, you can use composition instead of inheritance.
That is, add a private field in a forwarding class to reference the instance of the existing class. The methods in the forwarding class correspond to the methods of the existing class.
The Code is as follows:
import java.util.Collection;import java.util.Iterator;import java.util.Set;public class ForwardingSet<E> implements Set<E> { private final Set<E> s; public ForwardingSet(Set<E> s) { this.s = s; } public void clear() { s.clear(); } public boolean contains(Object o) { return s.contains(o); } public boolean isEmpty() { return s.isEmpty(); } public int size() { return s.size(); } public Iterator<E> iterator() { return s.iterator(); } public boolean add(E e) { return s.add(e); } public boolean remove(Object o) { return s.remove(o); } public boolean containsAll(Collection<?> c) { return s.containsAll(c); } public boolean addAll(Collection<? extends E> c) { return s.addAll(c); } public boolean removeAll(Collection<?> c) { return s.removeAll(c); } public boolean retainAll(Collection<?> c) { return s.retainAll(c); } public Object[] toArray() { return s.toArray(); } public <T> T[] toArray(T[] a) { return s.toArray(a); } @Override public boolean equals(Object o) { return s.equals(o); } @Override public int hashCode() { return s.hashCode(); } @Override public String toString() { return s.toString(); }}
In use, the forwarding class is directly inherited:
public class InstrumentedSet<E> extends ForwardingSet<E> { private int addCount = 0; public InstrumentedSet(Set<E> s) { super(s); } @Override public boolean add(E e) { addCount++; return super.add(e); } @Override public boolean addAll(Collection<? extends E> c) { addCount += c.size(); return super.addAll(c); } public int getAddCount() { return addCount; }}
Forwarding class provides corresponding methods through the Set interface.
This design also has its flexibility. inheritance can only select a specific implementation of Set, but we can choose any interface implementation with composite.
For example:
public static void main(String[] args) { InstrumentedSet<String> s = new InstrumentedSet<String>( new HashSet<String>()); s.addAll(Arrays.asList("Snap", "Crackle", "Pop")); System.out.println(s.getAddCount());}
How to choose between inheritance and combination?
The abstract statement is that inheritance is used only when the child class and the parent class do have a "is-a" relationship. Otherwise, the combination is used.
Or the actual point is that if TypeB only needs part of the behavior of TypeA, you should consider using composite.