Which two reasons should you use interfaces instead of abstract classes?
A. You expect that classes that implement your interfaces have many common methods or fields, or require access modifiers other than public.
B. You expect that unrelated classes would implement your interfaces.
C. You want to share code among several closely related classes.
D. You want to declare non-static on non-final fields.
E. You want to take advantage of multiple inheritance of type.
题解
选项 A,界面定义的成员一定是 public 可见度,所以这不是正确答案。
选项 B,如果说 A 继承 B 是「A 是 B (A is B)」的关系,那么 A 实作 B 可以说是「A 能做到 B 能做的事(A is capable of doing what B can do)」。也就是说,界面比较像是提供对象功能方面的描述,例如有个界面叫作「Walkable」(能走),定义了「walk」(走路)的方法,然后有个「Human」(人)这个类别,实作了「Walkable」界面。「Human」和「Walkable」并没有什么直接的关系,任何类别都可以实作这个界面来表示类别能做到走路这个动作。因此这个选项的叙述是正确的。
选项 C,界面除了特殊的预设方法和静态方法用法之外,是没办法共享程序实作的。
选项 D,界面的字段一定会使用 public static final 来进行修饰。
选项 E,一个类别可以实作多个界面。
