Java Reference
In-Depth Information
•
The default
CharitySinger.getRate()
method
The abstract
•
Employee.setRate()
method
The concrete
Employee.getRate()
method
There is no conflict for the
sing()
method. Therefore, the
Manager
class inherits the
sing()
method from the
CharitySinger
interface. There are two choices for the
setRate()
and
getRate()
methods. The two methods are
available in the superclass. Therefore, the
Manager
class inherits the
setRate()
and
getRate()
methods from the
Employee
class.
•
Example #2
The “superclass always wins” rule implies that the methods declared in the
Object
class cannot be overridden with a
default method in an interface. The following declaration for the
Runner
interface will not compile:
// Won't compile
public interface Runner {
void run();
// Not allowed
default String toString() {
return "WhoCares";
}
}
Before I give the reasons behind this rule, let's assume that the
Runner
interface compiles. Suppose a
Thinker
class implements the
Runner
interface as shown:
public class Thinker implements Runner {
public void run() {
System.out.println();
}
// Which method is inherited - Object.toString() or Runner.toString()?
}
The
Thinker
class has two choices for inheriting the
toString()
method: one from the superclass
Object
and
one from the superinterface
Runner
. Remember that the superclass always wins, and therefore, the
Thinker
class
inherits the
toString()
method from the
Object
class, not the
Runner
interface. This argument is true for all methods
in the
Object
class and all classes. Because such default methods in an interface will never be used by any class, it is
not allowed for interfaces to override the methods of the
Object
class with a default method.
Example #3
Default methods in interfaces cannot be declared final for two reasons:
•
Default methods are intended to be overridden in classes.
•
If a default method is added in an existing interface, all implementing classes should continue
to work if they contained a method with the same signature.