2014-03-25 94 views
2

我与Java 8摆弄,并来到了下面的代码在我看来可能工作:在接口从默认的方法内访问超级方法

class UnrelatedClass implements UnrelatedInterfaceDefault { 
    @Override 
    public void unrelate2() { 
     System.out.println("Unrelated"); 
    } 
} 

interface UnrelatedInterfaceDefault extends UnrelatedInterfaceOne, UnrelatedInterfaceTwo { 
    default public void unrelate() { 
     UnrelatedInterfaceOne.super.unrelate2(); 
     UnrelatedInterfaceTwo.super.unrelate2(); 
    } 
} 

interface UnrelatedInterfaceOne { 
    public void unrelate2(); 
} 

interface UnrelatedInterfaceTwo { 
    public void unrelate2(); 
} 

UnrelatedInterfaceOne.super.unrelate(),我得到的错误:

abstract method unrelate2() in UnrelatedInterfaceOne cannot be accessed directly. 

但考虑我是否创建一个实现UnrelatedInterfaceDefault一类的话,我其实有实现的UnrelatedInterfaceOneUnrelatedInterfaceTwo,所以它可以工作?

为什么在这种情况下会出现这个特定的编译器错误?

+0

为了使您的工作如预期,你可以使用强制类型转换为相应的接口,而不是调用超。例如。 '((UnrelatedInterfaceOne)此).unrelate2();' – Balder

回答

4

这是失败的,因为您的接口中的方法是abstract。如果你制作了default,那么我猜它会编译。尽管我现在无法测试它。

JLS §15.12.3 - Compile-Time Step 3: Is the Chosen Method Appropriate?

If the form is TypeName . super . [TypeArguments] Identifier , then:

  • It is a compile-time error if the compile-time declaration is abstract.

还要注意的是,使用super方法的调用从未通过动态调度去。它不会调用重写的方法,而只会调用super类中定义的方法,或者在此情况下调用TypeName

0

我试着让你的例子工作。

正如@Rohit Jain所述,我需要改变abstract-> default。然后我有diamond probleminterface UnrelatedInterfaceDefault的权利。我用空方法解决了它。 就是这样,它的工作原理。至于我,结果是合乎逻辑的)请参见下面

public class Main { 

    public static void main(String[] args) throws IOException, Exception { 
     UnrelatedClass uc = new UnrelatedClass(); 
     uc.unrelate2(); 
     uc.unrelate(); 
    } 
} 

class UnrelatedClass implements UnrelatedInterfaceDefault { 

    @Override 
    public void unrelate2() { 
     System.out.println("Unrelated"); 
    } 
} 

interface UnrelatedInterfaceDefault extends UnrelatedInterfaceOne, UnrelatedInterfaceTwo { 

    @Override 
    public default void unrelate2() { 
    } 

    default public void unrelate() { 
     UnrelatedInterfaceOne.super.unrelate2(); 
     UnrelatedInterfaceTwo.super.unrelate2(); 
     unrelate2(); 
    } 
} 

interface UnrelatedInterfaceOne { 

    public default void unrelate2() { 
     System.out.println("relatedOne"); 
    } 
} 

interface UnrelatedInterfaceTwo { 

    public default void unrelate2() { 
     System.out.println("relatedTwo"); 
    } 
} 

输出:

Unrelated 
relatedOne 
relatedTwo 
Unrelated