gpt4 book ai didi

java - 与私有(private)方法冲突时在接口(interface)中调用默认方法

转载 作者:行者123 更新时间:2023-12-03 07:39:32 25 4
gpt4 key购买 nike

考虑下面的类层次结构。

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)
  • 这都是因为我将 ClassA.hello 标记为私有(private)。
  • 如果我将 ClassA.hello 标记为 protected 或删除可见性修饰符(即使其成为默认范围),则会显示编译器错误:The inherited method ClassA.hello() cannot hide the public abstract method in Myinterface

  • 但是,根据上面的异常堆栈跟踪, 我得到一个运行时非法访问错误。

    我不明白为什么在编译时没有检测到这个。有什么线索吗?

    最佳答案

    更新:好像真的是bug .
    类或父类(super class)方法声明总是优先于默认方法!default hello(...)来自 Myinterface 的方法允许您编写没有错误:

    ClassB b = new ClassB();
    b.hello();
    直到运行时,因为在运行时 hello(...)来自 ClassA 的方法具有最高优先级(但该方法是私有(private)的)。因此, IllegalAccessError发生。
    如果您删除默认 hello(...)来自接口(interface)的方法,您会得到相同的非法访问错误,但现在是在编译时。

    关于java - 与私有(private)方法冲突时在接口(interface)中调用默认方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64729556/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com