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

时间:2021-04-24 18:03:36

标签: java interface default-method name-conflict

考虑下面的代码。

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),但我想知道为什么在使返回类型不同后错误消失了。

0 个答案:

没有答案
相关问题