Java Reference
In-Depth Information
This time, the error is because of two reasons:
The interface inherits two default
getRate() methods, one from the CharitySinger interface
and one from the Player interface.
The interface inherits a default
setRate() method from the CharitySinger interface and an
abstract setRate() method from the Player interface.
This type of conflict was not possible before Java 8 as the default methods were not available. The compiler does
not know which method to inherit when it encounters a combination of abstract-default or default-default method.
To resolve such conflicts, the interface needs to override the method in the interface.
There are several ways to resolve the conflict. All involve overriding the conflicting method in the interface.
You can override the conflicting method with an abstract method.
You can override the conflicting method with a default method and provide a new
implementation.
You can override the conflicting method with a default method and call one of the methods of
the superinterfaces.
Let's resolve the conflict in the SingerPlayer interface. Listing 17-29 contains a declaration for the interface that
overrides the getRate() method with an abstract getRate() method. Any class implementing the SingerPlayer
interface will have to provide an implementation for the getRate() method.
Listing 17-29. Overriding the Conflicting Method with an Abstract Method
// SingerPlayer.java
package com.jdojo.interfaces;
public interface SingerPlayer extends Singer, Player {
// Override the getRate() method with an abstract method
@Override
double getRate();
}
The declaration in Listing 17-30 for the SingerPlayer resolves the conflict by overriding the getRate() method
with a default getRate() method, which simply returns a value 700.00. Any class implementing the SingerPlayer
interface will inherit the default implementation of the getRate() method.
Listing 17-30. Overriding the Conflicting Method with a Default Method
// SingerPlayer.java
package com.jdojo.interfaces;
public interface SingerPlayer extends Singer, Player {
// Override the getRate() method with a default method
@Override
default double getRate() {
return 700.00;
}
}
 
Search WWH ::




Custom Search