Java Reference
In-Depth Information
Sometimes an interface may want to access the override default methods of its superinterfaces. Java 8 introduced
a new syntax for calling the overridden default methods of direct superinterfaces from an interface. The new syntax
uses the keyword
super
as shown:
SuperInterfaceName.super.superInterfaceDefaultMethod(arg1, arg2...)
■
Using the keyword
super
, only the default methods of the direct superinterfaces can be accessed. accessing
default methods of the superinterfaces of superinterfaces are not supported by the syntax. You cannot access the abstract
methods of the superinterfaces using this syntax.
Tip
Listing 17-31 contains the declaration for the
SingerPlayer
that resolves the conflict by overriding the
getRate()
method with a default
getRate()
method. The method calls the
getRate()
method of the
Player
interface using
the
Player.super.getRate()
call, multiplies the value by 3.5, and returns it. It simply implements a rule that a
SingerPlayer
is paid minimum 3.5 times a
Player
is paid. Any class implementing the
SingerPlayer
interface will
inherit the default implementation of the
getRate()
method.
Listing 17-31.
Overriding the Conflicting Method with a Default Method That Calls the Method in the Superinterface
// SingerPlayer.java
package com.jdojo.interfaces;
public interface SingerPlayer extends Singer, Player{
// Override the getRate() method with a default method that calls the
// Player superinterface getRate() method
@Override
default double getRate() {
double playerRate = Player.super.getRate();
double singerPlayerRate = playerRate * 3.5;
return singerPlayerRate;
}
}
Listing 17-32 contains the code for the
CharitySingerPlayer
interface. It overrides the
setRate()
method
with an abstract method and the
getRate()
method with a default method. The
getRate()
method calls the default
getRate()
method of the
Player
interface.
Listing 17-32.
Overriding the Conflicting Methods in the CharitySinger Interface
// CharitySingerPlayer.java
package com.jdojo.interfaces;
public interface CharitySingerPlayer extends CharitySinger, Player {
// Override the setRate() method with an abstract method
@Override
void setRate(double rate);
// Override the getRate() method with a default method that calls the
// Player superinterface getRate() method
@Override