5 回答
TA贡献1884条经验 获得超4个赞
看第5.9
章:Why interfaces
原文如下:
An interface is a contract (or a protocol, or a common understanding) of what the classes can do. When a class implements a certain interface, it promises to provide implementation to all the abstract methods declared in the interface. Interface defines a set of common behaviors. The classes implement the interface agree to these behaviors and provide their own implementation to the behaviors. This allows you to program at the interface, instead of the actual implementation. One of the main usage of interface is provide a communication contract between two objects. If you know a class implements an interface, then you know that class contains concrete implementations of the methods declared in that interface, and you are guaranteed to be able to invoke these methods safely. In other words, two objects can communicate based on the contract defined in the interface, instead of their specific implementation.
Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple inheritance permits you to derive a subclass from more than one direct superclass. This poses a problem if two direct superclasses have conflicting implementations. (Which one to follow in the subclass?). However, multiple inheritance does have its place. Java does this by permitting you to "implements" more than one interfaces (but you can only "extends" from a single superclass). Since interfaces contain only abstract methods without actual implementation, no conflict can arise among the multiple interfaces. (Interface can hold constants but is not recommended. If a subclass implements two interfaces with conflicting constants, the compiler will flag out a compilation error.)
TA贡献1866条经验 获得超5个赞
建议你选一本讲解设计模式的数看看,学习学习你就知道为什么要这么做了。
假设我有需要一个日志类,但是我并不确定日志要如何写入(日志也许会写入到文件里,也可能写入到数据库,并且我需要保证随时切换写入点),那这时候不同的写入方式代码一定是有有所区别的。这时候我们就需要定义多个日志类,DbLog
、FileLog
……而在程序中,如果不使用接口,你如何去使用它,难道一旦切换日志就把所有的代码修改一遍吗?当然不是,你只要让DbLog
、FileLog
……都实现一个接口Log
,在程序中使用Log
所定义的方法,则我们可以通过传入不同的实例轻松的切换日志写入方式。
TA贡献1829条经验 获得超7个赞
我的理解是接口是一种规范,可以表示实现了某接口的类一定有某些函数。接口有一个很实用的特性是可以用接口变量引用实现了该接口的对象,也就是说AA类实现了A接口的话,可以这样写:A a=new AA()。试想一下,如果你写了如下的代码给别人用:
void show(A a) {
a.print();
}
你如果想用别人传过来的a对象的print()函数,你怎么确保它这个a对象一定有print()函数?但如果你的A是个接口的话, 则别人想调用你写的show(),一定要写一个实现了A接口,有print函数的类作为参数。也就是说,你写的接口部分地规范了要实现你这个接口的类的代码。
添加回答
举报