Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java implementing two interfaces and resolving default method conflicts: why using super keyword?

Java resolving default method conflicts: why using super keyword?

I'm reading the book "Core Java SE 9 for the impatient". In section "Resolving Default Method Conflicts", I found that when resolving default method conflicts, the super keyword is used. But I don't understand why use the super keyword.

From this link: https://docs.oracle.com/javase/tutorial/java/IandI/override.html I know that the super keyword is required(otherwise the program won't compile).

But it seems counterintuitive. From my understanding, interface "Identified" has no super class. Why not just use "return Identified.getId();" ?

public interface Person {
    default int getId() {
        return 0;
    }
}

public interface Identified {
    default int getId() {
        return Math.abs(hashCode());
    }
}

public class Employee implements Person, Identified {
    public int getId() {
        return Identified.super.getId();
    }
}

There are some explanations in this question and this question but none of them explained why keyword super is used.

like image 524
CodingNow Avatar asked Mar 03 '18 04:03

CodingNow


1 Answers

Because Identified.getId() would imply that getId is a static method. Before Java 8, this super keyword was only used to refer to a super class in the form of super.getId().

In your case, Identified.super.getId() does not mean "The getId() of the super of Identified", but rather "The getId() of the super that is from Identified".

like image 164
T Tse Avatar answered Nov 12 '22 06:11

T Tse