借口是为了实现多重继承。 如:class Animal {} class Cat extends Animal implements Jumpable{ // can't fly void jump(){ //the jump style of cat } } class Bird extends Animal implements Flyable,Jumpable { void jump() { //the jump style of bird } void fly() { //the fly style of bird } } interface Flyable { void fly(); } interface Jumpable { void jump(); } public class Earth { Animal[] all = ...; public void allJump() for(int i = 0; i < all.length; i ++) all[i].jump(); } public void allFly() { for(int i = 0; i < all.length; i ++) { if(all[i] instancesof Flyable) all[i].jump(); } } }
在Java Tutorial中已经描述得很清楚。 You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following: ·Capturing similarities among unrelated classes without artificially forcing a class relationship. ·Declaring methods that one or more classes are expected to implement. ·Revealing an object's programming interface without revealing its class. ——http://java.sun.com/docs/books/tutorial/java/concepts/interface.html 更多的interface参考 http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html#238680
注意!实现接口与继承并不是一回事。 继承描述的是一种“父子”、“根-派生”的关系,是一种强耦合的逻辑关系; 接口只是描述一组共同的行为或者是一组规范,实现接口只是声明拥有这组共同的行为或声明遵循这组规范,在逻辑上关系比继承要弱。 或者用另一种方法描述二者的差别: 继承是“is a kind of”的关系,实现接口是"seems like "的关系。
如:class Animal {} class Cat extends Animal implements Jumpable{ // can't fly
void jump(){
//the jump style of cat
}
} class Bird extends Animal implements Flyable,Jumpable {
void jump() {
//the jump style of bird
}
void fly() {
//the fly style of bird
}
} interface Flyable {
void fly();
} interface Jumpable {
void jump();
} public class Earth {
Animal[] all = ...;
public void allJump()
for(int i = 0; i < all.length; i ++)
all[i].jump();
}
public void allFly() {
for(int i = 0; i < all.length; i ++) {
if(all[i] instancesof Flyable)
all[i].jump();
}
}
}
You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:
·Capturing similarities among unrelated classes without artificially forcing a class relationship.
·Declaring methods that one or more classes are expected to implement.
·Revealing an object's programming interface without revealing its class.
——http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
更多的interface参考
http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html#238680
这是因为:
JAVA 不能实现多重继承,只能实现单一继承。这在一定程度上硬性保证了
继承的有序性,但是有的时候这种机制显得有点呆板,如需要添加本类代表现实对象所不具有的特性或者方法,于是JAVA又提供了接口这个特殊的“补丁”来实现
多重继承。但是这个补丁的用处实在是很大....
可以将一些东西规范在众多接口里面,任你选购或者创造。。
继承描述的是一种“父子”、“根-派生”的关系,是一种强耦合的逻辑关系;
接口只是描述一组共同的行为或者是一组规范,实现接口只是声明拥有这组共同的行为或声明遵循这组规范,在逻辑上关系比继承要弱。
或者用另一种方法描述二者的差别:
继承是“is a kind of”的关系,实现接口是"seems like "的关系。