interface 不是一个 class 而是一组 requirements (自我感觉就是来多继承的,人家 cpp 就能无痛多继承)
发比方来说,你满足我的 requirements,我将会为你提供 service。比如,Array
会给 implements 了 Comparable
的类,提供排序服务
interface 中只能有方法和常量字段。Just as methods in an interface are automatically public
, fields are always public static final
.
Multiple Interfaces
class Employee implements Cloneable, Comparable
想要我的类既可以被深复制,又可以被比较
用于比较的接口
The Comparable Interface
意为“这个类型是可比较的”
常用书写规范
又是出于自反性的考虑,跨继承的两个类比较应当提前预判不给比,因为 cast 是单向的。要么就提前考虑好,在父类,并且 final
掉,不让重写了
为什么一定要接口,而不是让类自己定义一下呢?
因为 Java 是强制类型的,他得知道确实有这个
compareTo
,而 interface 就保证了这一点至于为什么不用类似函数对象之类的东西,应该是为了无痛吧 (纠正,其实是有的,后面讲了)
The Comparator Interface
意为“一个比较算子”。跟 C++的函数对象就很像了,或者函数指针
这是一个 functional interface,可以用 Lambda Expressions 简化
同时,如果比较很简单,就连用 lambda 都懒得用了,可以使用 comparing
再简化。比较默认从小到大,使用 reversed
来反转
Interface vs. Abstract Class
You can think of an interface as an abstract class with no instance fields. 就像开头所说,真的就是用来解决多继承的问题。
C++ Note review
C++ has multiple inheritance and all the complications that come with it, such as virtual base classes, dominance rules, and transverse pointer casts. Few C++ programmers use multiple inheritance, and some say it should never be used. Other programmers recommend using multiple inheritance only for the “mix-in” style of inheritance. In the mix-in style, a primary base class describes the parent object, and additional base classes (the so-called mix-ins) may supply auxiliary characteristics. That style is similar to a Java class with a single superclass and additional interfaces.
Static and Private Methods
Default Methods
可以有可实现的静态方法,一般是工厂函数 (?)