Java Reference
In-Depth Information
Comparable<FictionalCharacter>
FictionalCharacter
Superhero
Villain
FIGURE 8.6:
Inheritance hierarchy.
public
FictionalCharacter(String name)
{
this
.name = name;
}
public
String getName ()
{
return
name ;
}
public void
setName( String name)
{
this
.name = name;
public abstract double
computeStrength() ;
public int
compareTo(FictionalCharacter other)
{
if
(computeStrength()
>
other . computeStrength() )
{
return
1;
if
(computeStrength()
<
other . computeStrength() )
{
return
−
1;
return
0;
}
}
The
implements
keyword is used to denote that objects of type
FictionalCharacter
will be comparable. Note that the interface
Comparable
is generic. The type parameter de-
scribes the input type of the
compareTo
method. In other words, since the
compareTo
method takes as input an object of type
FictionalCharacter
,wemustimplement
Comparable<FictionalCharacter>
. The inheritance hierarchy for our example is shown
in Figure 8.6.
Let us now look at the
compareTo
method. Consider the following call.
if
(batman . compareTo(superman)
>
0)
{
...
}
The method call will return 1 if Batman has more strength, -1 if Superman has more
strength, or 0 if they have equal strength. In this case,
batman
is the hidden parameter
(or the
this
object). The
other
object formal parameter in the
compareTo
method will
become equal to
superman
.
First, note that we could have tried to use this alternative syntax for the
compareTo
method.
public int
compareTo(FictionalCharacter other)
{