interface is not for multi-inheritance at all!what can you inherit anyway? It does not have any implementation.Treat interface as a protocol, as a data type. for example, in functionkill(Person p) { p.die(); } you really don't care how the Person is implemented, as long as it supports the die() method.So it make sense to have Person as an interface.
to fishone(fishone) 在“鸟”的接口中,根本就没有鸟的特性,那么这个接口有用吗?也有用啊,可以知道你是鸟啊。也就是java.io.Serialzation一样。
Serializable, Cloneable, blahblahable are hacks. a framework relying on RTTI/reflection is not a good framework unless you don't have any other way around. Having an interface without methods is appropriate when you need to provide better type protection. But when you need to use "instanceof" or "isInstance", that's a sign of bad design.in jdk, er interfaces, optional methods(NonSupportedOperationException) are so ugly!
interface 中所有方法都没有实现。
最顶端的类一般都是设计为interface,它比abstract class更加抽象,更加灵活。大大的有用,一般类层次设计都是由interface开始。
举个最简单的例子:现在有“人”和“鸟”两个类,如果我想创造“超人”这个类,我就应该继承“人”,然后实现“鸟”的接口,达到会飞的目的。你觉得呢?:)
在“鸟”的接口中,根本就没有鸟的特性,那么这个接口有用吗?
不知interface能用在哪?
我觉得可以这样理解抽象类和接口:
首先,采用他们都是为了禁止生成该类的实例,作为一个父类使用;
第二,抽象类中可以有成员变量,可以有抽象方法(需要继承他的子类去实现,如果他的子类没有实现该抽象方法,则该子类也必须是个抽象类!),也可以有带有方法实体的方法;
而在接口中,只定义一些公共的方法名及其参数列表(同样需要实现(其实就是继承)他的类去实现,也同样如果实现他的类没有实现接口中定义的方法,则此类也必须是个抽象类!)。接口中没有成员变量,但它可以定义常量(必须初始化),但一般不这样做(除非一定要用接口进行常量管理),以保证接口的整洁。
第三,由于java中的单继承性,所以要想实现多重继承,只能由接口去实现。
所以,抽象类和接口适用的原则是:大多数情况下,应该首选接口去实现,除非确实需要带有成员变量(或是带有方法实体的方法),再选择抽象类。
{
p.die();
}
you really don't care how the Person is implemented, as long as it supports the die() method.So it make sense to have Person as an interface.
在“鸟”的接口中,根本就没有鸟的特性,那么这个接口有用吗?也有用啊,可以知道你是鸟啊。也就是java.io.Serialzation一样。
a framework relying on RTTI/reflection is not a good framework unless you don't have any other way around. Having an interface without methods is appropriate when you need to provide better type protection. But when you need to use "instanceof" or "isInstance", that's a sign of bad design.in jdk, er interfaces, optional methods(NonSupportedOperationException) are so ugly!