Inheritance disadvantage

Unlike method invocation, inheritance violates encapsulation. Since you don't know the super class implementation which may involve some unpredictable calling between different methods of super class. And it is difficult to maintain the subclass when there is a change of the super class.

Be careful with the interaction between inner methods of the superclass. Here is the demo.

package com.effectivejava.classinterface;

import java.util.Collection;

import java.util.Set;

/**

* @author Kaibo

*

*/

// Wrapper class - uses composition in place of inheritance

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() {

/* If you directly extends one implementation such as HashSet<E> of the Set<E> interface you will get the wrong addCount since the addAll method invoke the add method internally which has been override by your sub class.

*/

return addCount;

}

}

/**

* Implementation of prefer to composite to inherence.

*/

package com.effectivejava.classinterface;

import java.util.Collection;

import java.util.Iterator;

import java.util.Set;

/**

* @author Kaibo

*

*/

// Reusable forwarding class

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();

}

}

Wrapper class (Composite) disadvantage

Wrapper classes are not suited for use in callback frameworks, wherein objects pass self-references to other objects for subsequent invocations ("callbacks").

To avoid the method invoke subclass's overrided version

You can eliminate a class's self-use of overridable methods mechanically, without changing its behavior. Move the body of each overridable method to a private "helper method" and have each overridable method invoke its private helper method. Then replace each self-use of an overridable method with a direct invocation of the overridable method's private helper method.

Effective Java 16 Favor composition over inheritance的更多相关文章

  1. Effective Java 26 Favor generic types

    Use generic types to replace the object declaration Add one or more type parameters to its declarati ...

  2. Effective Java 27 Favor generic methods

    Static utility methods are particularly good candidates for generification. The type parameter list, ...

  3. Effective Java 60 Favor the use of standard exceptions

    Benefits to reuse preexisting exceptions It makes your API easier to learn and use. Programs using y ...

  4. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  5. 《Effective Java》读书笔记 - 4.类和接口

    Chapter 4 Classes and Interfaces Item 13: Minimize the accessibility of classes and members 一个好的模块设计 ...

  6. Effective Java Chapter4 Classes and Interface

    MInimize the accessibility of classes and members 这个叫做所谓的 information hiding ,这么做在于让程序耦合度更低,增加程序的健壮性 ...

  7. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  8. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  9. 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法

    Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...

随机推荐

  1. Android学习笔记之图片轮播...

    PS:一个bug又折腾了一个下午....哎... 学习内容: 1.Android利用ViewPager和PagerAdapter实现图片轮播... 2.使用反射机制获取Android的资源信息... ...

  2. jquery选中下拉列表的某个值

    $('#villageToiletAnn').val('xxx'); id是select的ID,不是option的ID

  3. HTML简明教程(二)

    HTML简明教程(二) 一.HTML 图像 二.HTML 表格 三.HTML 列表 四.HTML div和 span 五.HTML 布局 六.HTML 表单和输入 七.HTML 框架 八.HTML内联 ...

  4. CentOS6.5菜鸟之旅:安装rpmforge软件库

    一.rpmforge软件库    rpmforge是包含4000多种CentOS软件的软件库,被CentOS社区认为是安全和稳定的软件库. 二.安装rpmforege       1. 在http:/ ...

  5. Swift可空(Optional)类型基础

    可空类型,对于熟悉C#的同学一定不会陌生.在C#里面值类型都是不能为空的,比如int类型默认为0,bool默认为false.但是我们给int加上?后,就是一个可空类型了. 那么Swift里面呢.Swi ...

  6. phpBB论坛 代码 语法高亮 模块 Codebox Plus

    phpBB代码语法高亮模块 Codebox Plus Code-By.Org (https://www.phpbb.com/customise/db/mod/codebox_plus/) (https ...

  7. thread_LockSupport

    LockSupport是用来创建锁和其他同步类的基本线程阻塞原语. LockSupport中的park() 和 unpark() 的作用分别是阻塞线程和解除阻塞线程,而且park()和unpark() ...

  8. 在存储过程中调用WebService

    1 create procedure usp_CallWebServices 2 ( 3 @parameter nvarchar(500)=null 4 ) 5 as 6 Declare @obj i ...

  9. WinFrom子窗体向父窗体传值

    父窗框mainForm;子窗体childForm,利用事件进行传值 在子窗体中的操作: public event EventHandler accept;public string value; pr ...

  10. csharp: Speech

    Speech SDK 5.1https://www.microsoft.com/en-us/download/details.aspx?id=10121 detects mobile devices ...