Java Reference
In-Depth Information
@Override
default double getRate() {
return 0.0;
}
}
The
setRate()
method is a no-op. The
getRate()
method returns zero. The class that implements the
CharitySinger
interface will need to implement the
sing()
method and provide an implementation for it. The class
will inherit the default methods
setRate()
and
getRate()
.
It is possible that the same person is a singer as well as a writer. You can create an interface named
SingerWriter
,
which inherits from the two interfaces
Singer
and
Writer
, as shown in Listing 17-27.
Listing 17-27.
A SingerWriter Interface That Inherits from Singer and Writer Interfaces
// SingerWriter.java
package com.jdojo.interfaces;
public interface SingerWriter extends Singer, Writer {
// No code
}
How many methods does the
SingerWriter
interface have? It inherits three abstract methods from the
Singer
interface and three abstract methods from the
Writer
interface. It inherits methods
setRate()
and
getRate()
twice - once from the
Singer
interface and once from the
Writer
interface. These methods have the same declarations
in both superinterfaces and they are abstract. This does not cause a problem as both methods are abstract. The class
that implements the
SingerWriter
interface will need to provide implementation for both methods only once.
Listing 17-28 shows the code for a
Melodist
class that implements the
SingerWriter
interface. Note that it
overrides the
setRate()
and
getRate()
methods only once.
Listing 17-28.
A Melodist Class That Implements the SingerWriter Interface
// Melodist.java
package com.jdojo.interfaces;
public class Melodist implements SingerWriter {
private String name;
private double rate = 500.00;
public Melodist(String name) {
this.name = name;
}
@Override
public void sing() {
System.out.println(name + " is singing.");
}
@Override
public void setRate(double rate) {
this.rate = rate;
}