Java Reference
In-Depth Information
I1.m()
and
I2.m()
. In this case,
I2.m()
is considered most specific as it overrides
I1.m()
. I will summarize this rule
as follows:
•
Make a list of all choices of the method with the same signature that are available from
different superinterfaces.
•
Remove all methods from the list that have been overridden by others in the list.
•
Consider the following
Employee
class. It implements
Singer
and
SingerPlayer
interfaces.
If you are left with only one choice, that is the method the class will inherit.
public class Employee implements Singer, SingerPlayer {
// Code goes here
}
There are no conflicts in inheriting the
play()
methods, which is inherited from the
SingerPlayer
interface.
There is no conflict in inheriting the
sing()
method as both superinterfaces leads to the same
sing()
method that is
in the
Singer
interface.
Which
setRate()
method is inherited by the
Employee
class? You have the following choices:
•
Singer.setRate()
SingerPlayer.setRate()
Both choices lead to an abstract
setRate()
method. Therefore, there is no conflict. However, the
SingerPlayer.setRate()
method is most specific in this case as it overrides the
Singer.setRate()
method.
Which
getRate()
method is inherited by the
Employee
class? You have the following choices:
•
•
Singer.getRate()
SingerPlayer.getRate()
The
Singer.getRate()
method has been overridden by the
SingerPlayer.getRate()
method. Therefore,
Singer.getRate()
is removed as a choice, which leaves you only one choice,
SingerPlayer.getRate()
. Therefore,
the
Employee
class inherits the default
getRate()
method from the
SingerPlayer
interface.
•
The Class Must Override the Conflicting Method
If the above two rules were not able to resolve the conflicting method's inheritance, the class must override the
method and choose what it wants to do inside the method. It may implement the method in a completely new way
or it may choose to call one of the methods in the superinterfaces. You can call the default method of one of the
superinterfaces of a class using the following syntax:
SuperInterfaceName.super.superInterfaceDefaultMethod(arg1, arg2...)
If you want to call one of the methods in the superclass of a class, you can use the following syntax:
ClassName.super.superClassMethod(arg1, arg2...)
Consider the following declaration for a
MultiTalented
class, which inherits from the
Singer
and
Player
interfaces:
// Won't compile
public abstract class MultiTalented implements Singer, Player {
}