Search code examples
javainterfacedefault

JAVA, cannot bypass the more specific direct super type


I'm learning about interfaces. What happens here? and why I get a message:

"Illegal reference to super type SomeInterface2, cannot bypass the more specific direct super type 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();
    }
}

Solution

  • you can not access the default method of SomeInterface2,because it's super interface of SomeInterface3.as implementing class, ClassImplementingInterface only can visit its direct super interface's default method.from a logical point of view,that ClassImplementingInterface implements both interface SomeInterface2 and SomeInterface3,but SomeInterface2 is super interface,it seems unreasonable,if you have to do so,try following program.

    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();
        }
    

    }