Effective Java-composite mode is better than inheritance

Source: Internet
Author: User

Inheritance is one of the ways to implement code reuse, but improper use can cause many problems.


Inheritance destroys encapsulation and it is dangerous to inherit from a specific class across the package access level.
That is, subclasses depend on the implementation details of the parent class.
If the implementation details of the parent class change, the subclass can be compromised.


For example, expand HashSet to record how many elements have been added since the HashSet instance was created.
HashSet has two methods for adding elements--add (e E) and AddAll (collection<? extends e> c).
Then overwrite these two methods before adding the number of records before the 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, add 3 elements through 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());}

The result is: wkiol1plrwjbf_fsaadij3wv64w978.jpg


The cause of this result is simple.
Refer to add (e E) and AddAll (collection<? extends e> c) in Abstractcollection, with only one paragraph of the throw new in Add (E E) Unsupportedoperationexception ();
and AddAll (collection<? extends e> c) has such a passage in the documentation comment:

* <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, just remove the overlay AddAll method.
However, this does not solve the fundamental problem, that is, the AddAll method of HashSet does not guarantee that it will not change in future releases.
That is, the subclass implementation relies on the implementation of the parent class, and the subclass is destroyed when the parent class changes.
Perhaps we can override the parent-class method of re-implementation, although solving the problem, but such thankless, meaningless.


In addition, the addition or removal of a parent class will also have an effect on the child class.
For example, a subclass extends a collection class, overwriting all methods of adding elements, checking the elements before adding them, and letting all elements satisfy a certain condition.
If, in later versions, the parent class adds new methods for adding elements, and the subclass does not overwrite the method, the illegal elements are added to the collection.


Conversely, this can happen.
Even if the implementation of the parent class is not a problem, you can break the constraints of the parent class because the subclass is not implemented properly.
For example, the parent class just adds a method that has the same signature and return type as the subclass.


Therefore, in order to deal with these situations, you can use compound mode (composition) instead of inheritance.
That is, add a private field in a forwarding class to refer to an instance of an existing class, and the method in forwarding class corresponds to the method 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 (); }}


Directly inherit forwarding class when used:

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;    }}


The forwarding class provides the appropriate method through the set interface.
This design also has its flexibility, inheritance can only select a specific implementation of set, but using composite we can choose any interface implementation.
Like what:

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 do I choose between inheritance and composition?
It is more abstract to say that inheritance is used only when subclasses and parent classes do exist "is-a" relationships, otherwise they are used as a composite.
Or compare the actual point is that if the TYPEB only need to typea part of the behavior, then consider using composite.

Effective Java-composite mode is better than inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.