Interface(Java)
- background and design goal
unlike C++, java doesn’t support multi-inheritance because of its complexity and inefficiency (???)
all classes in java must have one base class(except for Object), so multi inheritance of classes is not allowed in java, interface can simulate multi-inheritance. - merit and demerit
- applicable scene
a sorting algorithm may expect an object of type Comparable without knowing the specific type - constituent part && key points
declares only public method headers and public static final constants.
cannot be instantiated.
can extend several other interfaces.
example:
public interface Recyclable {
(public) boolean gc(GcMeta gcMeta);
}
public interface PeerService extends Recyclable {
void add(PeerInfo peerInfo);
PeerInfo get(String cid);
} - underlying principle
similar to prototypes - comparision with abstract class
– class Human extends Animal, Whistler // Error
– class Human extends Animal implements Whistler // OK
Unfortunately abstract class has some problems when representing universal properties : extending multi base classes is not allowed in java;
interface can represent universal properties, simulating multi-inheritance easily.
Java接口:模拟多重继承
本文探讨了Java中接口的设计目标和实现原理,解释了为何Java不支持多重继承及接口如何模拟这一特性。通过实例说明了接口在声明公共方法头和常量、扩展多个接口的应用场景。
1845

被折叠的 条评论
为什么被折叠?



