对于一个类实现多个接口的情况,因为接口只有抽象方法,具体方法只能由实现接口的类实现,在调用的时候始终只会调用实现类的方法(不存在歧义),因此不存在多继承的第二个缺点;而又因为接口只有静态的常量,但是由于静态变量是在编译期决定调用关系的,即使存在一定的冲突也会在编译时提示出错;而引用静态变量一般直接使用类名或接口名,从而避免产生歧义,因此也不存在多继承的第一个缺点。
对于一个接口继承多个父接口的情况也一样不存在这些缺点。
请看以下示例。
接口A:
Java代码
public interface InterfaceA {
int len = 1 ;
void output();
}
接口B:
Java代码
public interface InterfaceB {
int len = 2 ;
void output();
}
接口Sub继承接口A和接口B:
Java代码
public interface InterfaceSub extends InterfaceA, interfaceB { }
类Xyz实现接口Sub:
Java代码
public class Xyz implements InterfaceSub {
public void output() {
System.out.println( "output in class Xyz." );
}
public void outputLen( int type) {
switch (type) {
case InterfaceA.len:
System.out.println( "len of InterfaceA=." +type);
break ;
case InterfaceB.len:
System.out.println( "len of InterfaceB=." +type);
break ;
}
}
public static void main(String[] args) {
Xyz xyz= new Xyz ();
xyz .output();
xyz .outputLen();
}
以上代码不存在什么问题,但是如果试图编写以下存在冲突的代码,则会编译失败。
Java代码
Xyz xyz = new Xyz();
int len = xyz.len;
System.out.println(len);
由于引入了接口,java显得非常灵活,也使得java中的多态性更加富有魔力。
,java抽象类和接口和继承之间关