当接口中的默认方法与私有方法冲突时,调用默认方法。

20 浏览
0 Comments

当接口中的默认方法与私有方法冲突时,调用默认方法。

考虑以下的类层次结构。

class ClassA {
    private void hello() {
        System.out.println("Hello from A");
    }
}
interface Myinterface {
    default void hello() {
        System.out.println("Hello from Interface");
    }
}
class ClassB extends ClassA implements Myinterface {
}
public class Test {
    public static void main(String[] args) {
        ClassB b = new ClassB();
        b.hello();
    }
}

运行程序将会产生以下错误:

Exception in thread "main" java.lang.IllegalAccessError: tried to access method com.testing.ClassA.hello()V from class com.testing.Test
at com.testing.Test.main(Test.java:23)

1. 这是因为我将ClassA.hello标记为私有。

2. 如果我将ClassA.hello标记为受保护或者移除可见性修饰符(即将其设为默认范围),那么将会显示编译错误:

The inherited method ClassA.hello() cannot hide the public abstract method in Myinterface

然而,根据上面的异常堆栈跟踪,我得到了一个运行时的IllegalAccessError错误。

我无法理解为什么这在编译时没有被检测到。有什么线索吗?

0