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.