Effective Java 18 Prefer interfaces to abstract classes
Feature |
Interface |
Abstract class |
Defining a type that permits multiple implementations |
Y |
Y |
Permitted to contain implementations. |
N |
Y |
The implemented class must reside the class hierarchy. |
N |
Y |
Single inheritance |
N |
Y |
Easy to evolve |
N |
Y |
Advantages of Interfaces
- Existing classes can be easily retrofitted to implement a new interface.
- Interfaces are ideal for defining mixins.
- Interfaces allow the construction of nonhierarchical type frameworks. (Composite)
public interface Singer {
AudioClip sing(Song s);
}
public interface Songwriter {
Song compose(boolean hit);
}
public interface SingerSongwriter extends Singer, Songwriter {
AudioClip strum();
void actSensitive();
}
- Interfaces enable safe, powerful functionality enhancements .
// Concrete implementation built atop skeletal implementation
static List<Integer> intArrayAsList(final int[] a) {
if (a == null)
throw new NullPointerException();
return new AbstractList<Integer>() {
public Integer get(int i) {
return a[i]; // Autoboxing (Item 05)
}
@Override public Integer set(int i, Integer val) {
int oldVal = a[i];
a[i] = val; // Auto-unboxing
return oldVal; // Autoboxing
}
public int size() {
return a.length;
}
};
}
Simulated multiple inheritance
The class implementing the interface can forward invocations of interface methods to a contained instance of a private inner class that extends the skeletal implementation.
// Skeletal Implementation
public abstract class AbstractMapEntry<K, V> implements Map.Entry<K, V> {
// Primitive operations
public abstract K getKey();
public abstract V getValue();
// Entries in modifiable maps must override this method
public V setValue(V value) {
throw new UnsupportedOperationException();
}
// Implements the general contract of Map.Entry.equals
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> arg = (Entry<?, ?>) o;
return equals(getKey(), arg.getKey())
&& equals(getValue(), arg.getValue());
}
private static boolean equals(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
// Implements the general contract of Map.Entry.hashCode
@Override
public int hashCode() {
return hashCode(getKey()) ^ hashCode(getValue());
}
private static int hashCode(Object obj) {
return obj == null ? 0 : obj.hashCode();
}
}
Note
- Because skeletal implementationsare designed for inheritance, you should follow all of the design and documentation guidelines in Item 17.
- A minor variant on the skeletal implementation is the simple implementation. It differs by being not abstract. It's just simplest possible working implementation. You can use it as it stands or subclass it as circumstances warrant.
Summary
If you export a nontrivial interface, you should strongly consider providing a skeletal implementation to go with it. Once an interface is released and widely implemented, it is almost impossible to change. The best thing to do when releasing a new interface is to have as many programmers as possible implement the interface in as many ways as possible before the interface is frozen. Finally, you should design all of your public interfaces with the utmost care and test them thoroughly by writing multiple implementations
Effective Java 18 Prefer interfaces to abstract classes的更多相关文章
- Effective Java 53 Prefer interfaces to reflection
Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...
- Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...
- Effective Java 69 Prefer concurrency utilities to wait and notify
Principle Use the higher-level concurrency utilities instead of wait and notify for easiness. Use Co ...
- Effective Java 13 Minimize the accessibility of classes and members
Information hiding is important for many reasons, most of which stem from the fact that it decouples ...
- Effective Java 19 Use interfaces only to define types
Reason The constant interface pattern is a poor use of interfaces. That a class uses some constants ...
- Effective Java 35 Prefer annotations to naming patterns
Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...
- Effective Java 68 Prefer executors and tasks to threads
Principle The general mechanism for executing tasks is the executor service. If you think in terms o ...
- Effective Java 25 Prefer lists to arrays
Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...
- Effective Java 46 Prefer for-each loops to traditional for loops
Prior to release 1.5, this was the preferred idiom for iterating over a collection: // No longer the ...
随机推荐
- 基于HTML5的燃气3D培训仿真系统
最近上线了的基于HTML5的燃气3D培训仿真系统,以前的老系统是采用基于C++和OpenGL的OpenSceneGraph引擎设计的,OSG引擎性能和渲染效果各方面还是不错的,但因为这次新产品需求要求 ...
- 看看如何面试前端工程师:Github很重要
从程序员的角度提出要去学习哪些知识,下面这篇文章从面试官的角度介绍到面试时可能会问到的一些问题.不过我想先给你们一个忠告,招聘是一件非常艰巨的任务,在45分钟内指出一名侯选人是否合适是你需要完成的任务 ...
- 重构第22天 分解方法(Break Method)
理解:如果一个功能,里面比较复杂,代码量比较多,我们就可以把这个功能分解成多个小的method,每个方法实现该功能的一个小小的部分,并且方法命名成容易理解,和方法内容相关的名称,更有助于维护和可读性提 ...
- ASP.NET MVC中错误日志信息记录
MVC中有一个处理异常的过滤器 HandleErrorAttribute 1.新建一个类继承自 HandleErrorAttribute,然后重写OnException这个方法 public clas ...
- 关于window.onload,window.onbeforeload与window.onunload
★ window.onload 当页面加载完毕的时候执行,即在当前页面进行其他操作之前执行.如,刚进入某个网页的弹窗提示. ( 与window.onload相近的可以参考我写的另外一篇记录&qu ...
- BI之SSAS完整实战教程1 -- 开篇, BI简介 & SSAS简介
文章提纲 商业智能(BI, Business Intelligence)基本概念 SSAS(SQL Server Analysis Services)相关工具(开发.管理和客户端) 总结 一.商业智能 ...
- 雷军V5,米3横空出世
小米3 下午两点,小米CEO:雷军(也是一个传奇人物),虽然没购买门票,只是自己一个人看微博,看新闻,还是了解到了小米3的面貌,这次雷哥还给大家带来了MITV,售价¥2999!(无法相信)顶配.这次我 ...
- 六个创建模式之简单工厂模式(Simple Factory Pattern)
定义: 定义一个工厂类,它可以根据参数的不同生成对应的类的实例:被创建的类的实例通常有相同的父类.因为该工厂方法尝尝是静态的,所以又被称为静态工厂方法(Static Factory Method) 结 ...
- jQuery实现图片伦播效果(淡入淡出+左右切换)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Play 可以做的 5 件很酷的事
Play 可以做的 5 件很酷的事 本章译者:@Playframwork 通过 5 个实例,透视 Play 框架背后的哲学. 绑定 HTTP 参数到 JAVA 方法参数 用 Play 框架,在 Jav ...