The most critical role of interfaces is also the most important reason for using interfaces: they can be traced back to multiple basic classes. The second reason for using an interface is the same as for using an abstract base class: to prevent the client programmer from making an object of this class and specifying that it is just an interface. This brings up a question: Should I use an interface or an abstract class? If we use interfaces, we can get the benefits of abstract classes and interfaces at the same time. So if the base class you want to create does not have any method definitions or member variables, then you are willing to use an interface instead of an abstract class anyway. In fact, if you know in advance that something is going to be a base class, your first option is to turn it into an interface. Abstract classes should be considered only when method definitions or member variables must be used.
/** * Created by xfyou on 2016/11/3. * Java 继承和接口演示 */ public class Adventure { static void t(CanFight x) { x.fight(); } static void u(CanSwim x) { x.swim(); } static void v(CanFly x) { x.fly(); } static void w(ActionCharacter x) { x.fight(); } public static void main(String[] args) { Hero i = new Hero(); t(i); u(i); v(i); w(i); } } interface CanFight { void fight(); } interface CanSwim { void swim(); } interface CanFly { void fly(); } class ActionCharacter { // 父类中实现了子类中继承的接口方法 public void fight() { } } /** * 必须先 extends 然后再 impplements */ class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { @Override public void fly() { } @Override public void swim() { } }