考虑以下类层次结构。
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)
The inherited method ClassA.hello() cannot hide the public abstract method in Myinterface
但是,根据上面的异常堆栈跟踪,我得到一个运行时IllegalAccessError。
我无法理解为什么在编译时没有检测到这一点。有线索吗?
答案 0 :(得分:29)
更新:好像它真的是bug。
类或超类方法声明总是优先于默认方法!
来自default hello(...)
的 Myinterface
方法允许您无误写入:
ClassB b = new ClassB();
b.hello();
直到运行时,因为来自hello(...)
的运行时ClassA
方法具有最高优先级(但该方法是私有的)。因此,IllegalAccessError
发生。
如果从界面中删除默认的hello(...)
方法,则会出现相同的非法访问错误,但现在是在编译时。