[Valid Java] 6. Using Compound takes precedence over using inheritance, while using tivejava
This is what any book will say, because we often don't need to inherit, but just want to extend the class, and we want to extend the attributes or classes corresponding to the methods, at this time, if the relationship between the two is a, this relationship does exist, you can use inheritance, otherwise it is generally recommended to use combination.
If we do not know much about the internal logic when inheriting a class, some methods may be called internally by the class, when we inherit this method, we may overwrite some methods, overload some methods, or add some logic, in this way, the original logic is mixed with our own logic. If the inherited class uses this class internally, it will call some of the logic we write ourselves, then the results become unpredictable.
We recommend that you use the packaging mode.
Package cn. xf. cp. ch02.item16; import java. util. collection; import java. util. iterator; import java. util. set; public class ForwardingSet <E> implements Set <E> {/*** this class is used as the forwarding class, internally, set is used as a component by means of combination */private final Set <E> s; public ForwardingSet (Set <E> s) {this. s = s ;}@ Override public int size () {return s. size () ;}@ Override public boolean isEmpty () {return s. isEmpty () ;}@ Override public boolean contai Ns (Object o) {return s. contains (o) ;}@ Override public Iterator <E> iterator () {return s. iterator () ;}@ Override public Object [] toArray () {return s. toArray () ;}@ Override public <T> T [] toArray (T [] a) {return s. toArray (a) ;}@ Override public boolean add (E e) {return s. add (e) ;}@ Override public boolean remove (Object o) {return s. remove (o) ;}@ Override public boolean containsAll (Collection <?> C) {return s. containsAll (c) ;}@ Override public boolean addAll (Collection <? Extends E> c) {return s. addAll (c) ;}@ Override public boolean retainAll (Collection <?> C) {return s. retainAll (c) ;}@ Override public boolean removeAll (Collection <?> C) {return s. removeAll (c) ;}@ Override public void clear () {s. clear ();}}
In this way, we call the private member method in each method, so the private member is invisible to the outside, and the methods in it will not be mixed with the external methods.
Package cn. xf. cp. ch02.item16; import java. util. collection; import java. util. set;/*** function: Packaging class * Time: 9:58:36 * file: InstrumentedSet. java * @ author xiaof ** @ param <E> */public class InstrumentedSet <E> extends ForwardingSet <E> {private int addCount = 0; // used to count the number of elements added to the set: public InstrumentedSet (Set <E> s) {super (s) ;}@ Override public boolean add (E e) {++ addCount; return super. add (e) ;}@ Override public bo Olean addAll (Collection <? Extends E> c) {addCount + = c. size (); return super. addAll (c);} public int getAddCount () {return addCount ;}}