Calling interface's default method when superclass has private method

135 views Asked by At

Consider the code below.

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());
    }
}

This program yields an 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)

But if you replace the return value of A.f() with Integer or Object, no error will occur and the default method will be executed.

Why in the code snippet above IllegalAccessError occurs but after the described modification all works fine?

Both methods in the question Calling default method in interface when having conflict with private method have the same return type (namely, void), but I'm wondering why the error disappears after making return types different.

0

There are 0 answers