Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a method of superinterface called through Interface.super?

Tags:

java

When you extend a class in Java you can refer to base class' members through the super reference. However when you have a class A, that implements and interface B, you can only refer to B's methods in this way B.super.method(). Why does the super keyword in the second case have to be prefixed with B.?

Example:

interface Runner {
    default void run() {
        System.out.println("default Runner::run");
    }
}

static class RunnerImpl implements Runner {
    public void run() {
        Runner.super.run(); // doesn't work without "Runner."
    }
}
like image 717
Coder-Man Avatar asked Dec 07 '22 14:12

Coder-Man


2 Answers

Because interfaces allow multiple inheritance, which can result in ambiguity for identical methods:

interface Runner1 {
    default void run() {
        System.out.println("default Runner1::run");
    }
}

interface Runner2 {
    default void run() {
        System.out.println("default Runner2::run");
    }
}

static class RunnerImpl implements Runner1, Runner2 {
    public void run() {
        super.run(); // which one???
    }
}
like image 97
shmosel Avatar answered Apr 15 '23 03:04

shmosel


Because super.xyz() looks in the superclass (which you don't have, besides Object) and Type.super.xyz() will look for a class or interface, as defined in 15.12.1. Compile-Time Step 1: Determine Class or Interface to Search:

If the form is super . [TypeArguments] Identifier, then the class to search is the superclass of the class whose declaration contains the method invocation.

Notice, no interface mentioned.

If the form is TypeName . super . [TypeArguments] Identifier, then:

[...]

Otherwise, TypeName denotes the interface to be searched, I.

like image 36
Progman Avatar answered Apr 15 '23 03:04

Progman