Java 中的接口

来源:互联网 发布:mysql error code 1022 编辑:程序博客网 时间:2024/06/04 19:18

抽象类与抽象方法

Java中提供一个叫做抽象方法的机制,这种方法是不完整的:仅有声明而没有方法体。例如:

abstract void f();

包含抽象方法的类叫做抽象类。如果一个类包含一个或多个抽象方法,该类必须被限定为抽象的(否则,编译器就会报错)。抽象类是不完整的,因此不能定义抽象类的对象。


接口

You can choose to explicitly declare the methods in an interface as public, but thdy are public even if you don't say it. 可以明确声明接口中的方法为public的,但,即使你不声明,接口的方法也是public的。

So Wen you implement an interface, the methods from the interface must be defined as public. 因此,当你实现一个接口时,来自于接口的方法必须是定义为public的。

Otherwise, they would default to package access, and you'd be reducing the accessibility of a method during inheritance, which is not allowed bye the Java compiler. 否则,这些方法只有包访问权限,而在Java中是不允许降低继承而来的方法的访问权限。(C++中是可以)

An interface can also contain fields, but these are implicitly static and final. 接口也可以包含数据成员,但它们隐式的被声明为static与final的。

interface Instrument {int VALUE = 5; // static & final // Cannot have method definitionsvoid play (Note n); // Automatically public}

Java中的多继承

If you do inherit from a non-interface, you can inherit from only one. All the rest of the base elements must be interfaces. You place all the interface names after the implements keyword and separate them with commas. 一个类最多只能继承于一个非接口类,但可以承继与多个接口。多个接口跟在关键字implements之后,并以逗号分隔。

When you combine a concrete class with interfaces, the concrete class must come first, then the interfaces. 当一个类同时继承非接口类与接口类时, 必须先写非接口类,再写接口。例如

interface CanFight {void fight ();}interface CanSwim {void swim ();}class ActionCharacter {public void fight (){}}// 这里ActionCharacter只能写在implements之前class Hero extends ActionCharacter implements CanFight, CanSwim {public void swim () {}}
这里Hero类中并没有实现CanFight中的fight接口,但继承了ActionCharacter中的fight接口,在Java中这是允许的(C++中,这是不允许的)。

接口所要表达的是“All classes that implement this particular interface will look like this"。换句话说,只要继承者满足接口的要求(接口的方法已经定义),我们并不关心这些方法是重新定义的,还是继承而来。

This brings up a question: Should you use an interface or an abstract class? If it's possible to create your ase class without any method definitions or
member variables, you should always prefer interfaces to abstract classes. 那到底应该是使用接口,还是抽象类呢?建议是,在不需要方法定义以及数据成员时,都先考虑interface.

通过继承扩展接口

Normally, you can use extends with only a single class, but extends can refer to multiple base interfaces when building a new interface. 通常,在继承时,只能对一个类使用extends关键字, 但可能使用extends继承多个接口来创建一个新的接口。例如,以下接口Vampire

interface Monster { void menace ();}interface DangerousMonster extends Monster {void destroy ();}interface Lethal {void kill ();}class DragonZilla implements DangerousMonster {public void menace () {}public void destroy () {}}interface Vampire extends DangerousMonster, Lethal {void drinkBlood ();} 

接口中的数据成员都是final与static的,但接口中不能使用空白final





0 0
原创粉丝点击