JAVA,无法绕过更具体的直接超类型

时间:2016-01-09 13:01:37

标签: java interface default

我正在学习接口。这里发生了什么?为什么我收到一条消息:

  

“非法引用超类型SomeInterface2,无法绕过   更具体的直接超类型interfejsy.SomeInterface3“

public interface SomeInterface1 {       
    public default void action(){
        System.out.println("default interface1 method");
    };

}

public interface SomeInterface2 {
    public default void action(){
        System.out.println("default interface2 method");
    };
}

public interface SomeInterface3 extends SomeInterface2{

    public default void action(){
        System.out.println("default interface3 method");
    }
}

...

public class ClassImplementingInterface implements SomeInterface1, SomeInterface2, SomeInterface3{

    //Every interface has action() method so we have to override it
    @Override
    public void action() {
        SomeInterface1.super.action();
        SomeInterface2.super.action(); //---- compiler error
        SomeInterface3.super.action();
    }
}

1 个答案:

答案 0 :(得分:5)

  

您无法访问SomeInterface2的默认方法,因为   它是SomeInterface3.as实现类的超级接口,   ClassImplementingInterface只能访问其直接超级界面   默认方法。从逻辑上看,即   ClassImplementingInterface实现了两个接口SomeInterface2   和SomeInterface3,但SomeInterface2似乎是超级接口   不合理,如果你不得不这样做,请尝试按照程序。

public interface SomeInterface1 {       
    public default void action(){
        System.out.println("default interface1 method");
    };
}

public interface SomeInterface2 {
    public default void action(){
        System.out.println("default interface2 method");
    };
}

public interface SomeInterface3 extends SomeInterface2{
     public default void action(){
         System.out.println("default interface3 method");
     }
     public default void action2(){
         SomeInterface2.super.action();
     }
  }

public class ClassImplementingInterface implements SomeInterface1,SomeInterface2,SomeInterface3{
    public void action() {
        SomeInterface1.super.action();
        SomeInterface3.super.action2();
        SomeInterface3.super.action();
    }

}