我正在读一本关于 android 的书,但在一本迷你书中刷了一些 java 的东西。我已经读过一本关于 Java 的书并且了解接口(interface)。书上说
The interface-implementing hierarchy (if you can call it a “hierarchy”) cuts across the class-extension hierarchy. This idea is illustrated in Figure 4-1, where I display class extensions vertically and display interface implementations horizontally. (Android’s KeyboardView class lives in the android.inputmethod service package. Both KeyboardView and the homegrown MyListener class in Listing 4-3 implement Android’s OnClickListener interface.)
Burd, Barry (2011-11-14). Android Application Development All-in-One For Dummies (p. 197). John Wiley and Sons. Kindle Edition.
“跨越类层次结构的切割”是否仅仅意味着同级类都扩展了接口(interface)...我不明白他们用这个图还指出了什么,并说它水平地跨越了图 4 中的类垂直层次结构-3...请解释是否有比我从中得到的更深的特殊概念...
最佳答案
MyListener
和 KeyboardView
类都实现了 OnClickListener
接口(interface)。这使得这两个类都成为 OnClickListener
。
其思想如下:每个类都派生自基类(Object
是可用的最基本的类)。这使得每个类都成为对象
。从面向对象编程的角度思考,关于某物你能说的最抽象的事情是,它是一个对象。
回到接口(interface),假设您有两个接口(interface),Singer
和 Writer
。一个人可以是歌手,一个人可以是作家。但他/她也可以两者兼而有之。
实现Singer
和/或Writer
可以告诉您有关对象的更多信息。一些代码:
class Guy implements Singer, Writer{
// Empty
}
Guy chris = new Guy();
hireWriter(chris); // Accepts "Writer" as it's parameter
hireSinger(chris); // Accepts "Singer" as it's parameter
通过实现接口(interface),您可以告诉代码该对象是:
- 一个
对象
歌手
- 一个
作家
这种“贯穿类层次结构”的方式是通过实现接口(interface)而不是从更多类派生来提供有关类的更多信息。
关于java - 跨类层次结构的接口(interface) "Cutting",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11768861/