超类有私有方法时调用接口的默认方法

问题描述

考虑下面的代码

interface I {
    default Number f() {
        return 0;
    }
}

class A {
    private Number f() { // if Number is replaced with other type,all will work fine
        return 1;
    }
}

class B extends A implements I {
}

class Main {
    public static void main(String[] args) {
        System.out.println(new B().f());
    }
}

这个程序产生一个 IllegalAccessError

Exception in thread "main" java.lang.IllegalAccessError: class tasks.a1.Main tried to access private method 'java.lang.Number tasks.a1.A.f()' (tasks.a1.Main and tasks.a1.A are in unnamed module of loader 'app')
    at tasks.a1.Main.main(Sub.java:20)

但是如果将A.f()的返回值替换为IntegerObject,则不会出错,会执行方法

为什么在上面的代码片段中出现了 IllegalAccessError,但在描述的修改之后一切正常?

问题 Calling default method in interface when having conflict with private method 中的两种方法具有相同的返回类型(即 void),但我想知道为什么在使返回类型不同后错误消失了。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...