Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(九)之Interfaces
Interfaces and abstract classes provide more structured way to separate interface from implementation.
the abstract class, which is a kind of midway step between an ordinary class and an interface.
Abstract classes and methods
abstract void f();
A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the class itself must be qualified as abstract.
It's possible to make a class abstract without including any abstract methods. This is useful when you've got a class in which it doesn't make sense to have any abstract methods, and yet you want to prevent any instances of that class.
Abstract classes are also useful refactoring tools, since they allow you to easily move common methods up the inheritance hierarchy.
Interfaces
The interface keyword produces a completely abstract class, one that provides no implementation at all.
An interface says, "All classes that implement this particular interface will look like this."
The interface is used to establish a "protocol" between classes.
interface allowed multiple inheritance
An interface can also contain fields, but these are implicitly static and final.
You can choose to explicitly declare the methods in an interface as public, but they are public even if you don't say it. So wnen you implement an interface, the methods from the interface must be defined as public.
Complete decoupling
Creating a method that behaves differently depending on the argument object that you pass it is called the Strategy design pattern. The method contains the fixed part of the algorithm to be performed, and the Strategy contains the part that varies
The Strategy is the object that you pass in, and it contains code to be executed.
public static void process(Processor p, Object s) {
p.process(s);
}
public static void main (String[] args) {
process(new Upcase(),s);
process(new Downcase(),s);
}
However, you are often in the situation of not being able to modify the classes that you want to use. In these cases, you can use the Adapter design pattern.
class FilterAdapter implements Processor {
Filter filter;
public FilterAdapter (Filter filter) {
this.filter = filter;
}
public String name () { return filter.name();}
public Waveform process (Object input) {
return filter.process((Waveform)input);
}
"Multiple inheritance" in Java
A class can only extends one class, and can implements one or more interface
When you combine a concrets class with interfaces this way, the concrete class must come first, then the interfaces.
The resons for interfaces:
1. to upcast to more than one base type.
2. (the same as using an abstract base class) to prevent the client programmer from makig an object of this class and to establish that it is only an interface.
In fact, if you know somethins is going to be a base class, you can consider making it an interface.
Extending an interface with inheritance
You can easily add new method declarations to an interface by using inheritance, and you can also combine several interfaces into a new interface with inheritance.
Name collisions when combining interfaces
overloaded methods cannot differ only by return type.
Using the same method names in different interfaces that are intended to be combined generally causes confusion in the readability of the code, as well. Strive to avoid it.
Adapting to an interface
A common use for interfaces is the Strategy design pattern.
Fields in interfaces
Because any fields you put into an interface are automatically static and final, the interface is a convenient tool for creating groups of constant values. Before Java SE5, this was the only way to produce the same effect as an enum.
The fields in an interface are automatically public.
Initializing fields in interfaces
Fields defined in interfaces cannot be "blank finals", but they can be initialized with non-constant expressions.
the fields, of course, are not part of the interface. The values are stored in the static storage area for that interface.
Nesting interfaces
nesting an interface, these can have public 、package-access or private visibility.
Implementing a private interface is a way to force the definition of the methods in that interface without adding any type information.
package interfaces.nesting;
class A {
interface B {
void f();
}
public class BImp implements B {
public void f() {
}
}
private class BImp2 implements B {
public void f() {
}
}
public interface C {
void f();
}
class CImp implements C {
public void f() {
}
}
private class CImp2 implements C {
public void f() {
}
}
private interface D {
void f();
}
private class DImp implements D {
public void f() {
}
}
public class DImp2 implements D {
public void f() {
}
}
public D getD() {
return new DImp2();
}
private D dRef;
public void receiveD(D d) {
dRef = d;
dRef.f();
}
}
interface E {
interface G {
void f();
}
// Redundant "public":
public interface H {
void f();
}
void g();
// Cannot be private within an interface:
// ! private interface I {}
}
public class NestingInterfaces {
public class BImp implements A.B {
public void f() {
}
}
class CImp implements A.C {
public void f() {
}
}
// Cannot implement a private interface except
// within that interface’s defining class:
// ! class DImp implements A.D {
// ! public void f() {}
// ! }
class EImp implements E {
public void g() {
}
}
class EGImp implements E.G {
public void f() {
}
}
class EImp2 implements E {
public void g() {
}
class EG implements E.G {
public void f() {
}
}
}
public static void main(String[] args) {
A a = new A();
// Can’t access A.D:
// ! A.D ad = a.getD();
// Doesn’t return anything but A.D:
// ! A.DImp2 di2 = a.getD();
// Cannot access a member of the interface:
// ! a.getD().f();
// Only another A can do anything with getD():
A a2 = new A();
a2.receiveD(a.getD());
}
}
The rules about interfaces-- that all interfaces elements must be public--are strictly enforces here, so an interface nested within another interface is automatically public and cannot be made private.
Notice that when you implement an interface, you are not required to implement any interfaces nested within. Also, private interfaces cannot be implemented outside of their defining classes.
Interfaces and factories
An interfaces is intended to be a gateway to multiple implementations, and a typical way to produce objects that fit the interface is the Factory Method design pattern.
You call a creation method on a factory object which produces an implementation of the interface--this way, in theory, your code is completely isolated from the implementation of the interface.
Summary
Almost anytime you create a class, you could instead create an interface and a factory.
Interfaces should be something you refactor to when necessary, rather than installing the extra level of indirection everywhere, along with the extra complexity.
An appropriate guideline is to prefer classes to interfaces. Start with classes, and if it becomes clear that interfaces are necessary, then refactor. Interfaces are a great tool, but they can easily be overused.
Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(九)之Interfaces的更多相关文章
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control
Access control ( or implementation hiding) is about "not getting it right the first time." ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup
Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings
Immutable Strings Objects of the String class are immutable. If you examine the JDK documentation fo ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(二)之Introduction to Objects
The genesis of the computer revolution was a machine. The genesis of out programming languages thus ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十四)之Type Information
Runtime type information (RTTI) allow you to discover and use type information while a program is ru ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions
The ideal time to catch an error is at compile time, before you even try to run the program. However ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十一)之Holding Your Objects
To solve the general programming problem, you need to create any number of objects, anytime, anywher ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十)之Inner Classes
The inner class is a valuable feature because it allows you to group classes that logically belong t ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism
Polymorphism is the third essential feature of an object-oriented programming language,after data ab ...
随机推荐
- JavaScript 模式》读书笔记(4)— 函数1
从这篇开始,我们会用很长的章节来讨论函数,这个JavaScript中最重要,也是最基本的技能.本章中,我们会区分函数表达式与函数声明,并且还会学习到局部作用域和变量声明提升的工作原理.以及大量对API ...
- 告别炼丹,Google Brain提出强化学习助力Neural Architecture Search | ICLR2017
论文为Google Brain在16年推出的使用强化学习的Neural Architecture Search方法,该方法能够针对数据集搜索构建特定的网络,但需要800卡训练一个月时间.虽然论文的思路 ...
- 微信开发+百度AI学习:植物识别
直接上代码 服务端代码如下 private static readonly Baidu.Aip.ImageClassify.ImageClassify client = new Baidu.Aip.I ...
- 自定义实现 PyQt5 下拉复选框 ComboCheckBox
一.前言 由于最近的项目需要具有复选功能,但过多的复选框会影响界面布局和美观,因而想到把 PyQt5 的下拉列表和复选框结合起来,但在 PyQt5 中并没有这样的组件供我们使用,所以想要自己实现一个下 ...
- 题解 CF1304E 【1-Trees and Queries】
前言 这场比赛,在最后 \(5\) 分钟,我想到了这道题的 \(Idea\),但是,没有打完,比赛就结束了. 正文 题目意思 这道题目的意思就是说,一棵树上每次给 \(x\) 和 \(y\) 节点连 ...
- 贪心-Course Schedule III
2020-02-01 21:37:39 问题描述: 问题求解: 对于课程来说截止时间在前面的肯定需要优先安排,所以首先需要将courses按照deadline进行排序. 然后只需要不断的加入当前的课程 ...
- 用java分组查elasticsearch
哎,编程路漫漫,一坑又一坑,爬完还会掉,何时是尽头! 今朝有酒今朝醉,程序不对不敢睡! 还是接口昂,今天还是接口有问题,我是很菜,很笨,但是我还是要努力!! 正文: 接口需求是这样的,根据车型查询在线 ...
- Apache Druid 底层存储设计(列存储与全文检索)
导读:首先你将通过这篇文章了解到 Apache Druid 底层的数据存储方式.其次将知道为什么 Apache Druid 兼具数据仓库,全文检索和时间序列的特点.最后将学习到一种优雅的底层数据文件结 ...
- MFC之创建多级动态菜单
一开始以我是这样做的,结果是错误的: 这段代码第一次点击时,会在第6个位置创建MFC菜单,我本以为再次点击,menu->GetSubMenu(5)返回的值就不会为空了,但事实是它返回了NULL, ...
- Redis 缓存更新一致性
当执行写操作后,需要保证从缓存读取到的数据与数据库中持久化的数据是一致的,因此需要对缓存进行更新. 因为涉及到数据库和缓存两步操作,难以保证更新的原子性. 在设计更新策略时,我们需要考虑多个方面的问题 ...