Java Reference
In-Depth Information
8.9 The
final
Keyword
Sometimes, we want to create a method and disallow it to be overridden. In our example,
we may want to fix the way the
computeStrength
method works. In other words, we want
to make sure that someone does not create a class called
SpecialSuperhero
where the
strength is calculated in a different way. Maybe this class will give unfair advantage to
special superheroes. In order to prevent this, we can define the
computeStrength
method
in the
Superhero
class as
final
. Here is the rewritten code.
public class
Superhero
extends
FictionalCharacter
{
...
final double
computeStrength()
{
return
goodPower
∗
respect
∗
Math . random ( ) ;
}
...
}
A
final
method cannot be overridden in a subclass. Polymorphism does not apply
to final methods.
Similar to methods, classes can also be defined as
final
.A
final
class cannot be
inherited from. For example, consider the following code.
public final class
Superhero
extends
FictionalCharacter
{
...
}
This means that a
SpecialSuperhero
class that extends from the
Superhero
class
cannot be created.
8.10 Static Methods and Polymorphism
Note that polymorphism does not apply to static methods. In order to demonstrate
the consequences, we will add the
memberCount
static method to the
FictionalCharacter
class. The method will simply return the number of fictional characters that are created.
public abstract class
FictionalCharacter
implements
Comparable
<
>{
private
String name;
private static int
memberCount = 0;
public
FictionalCharacter ()
{
memberCount++;
}
public
FictionalCharacter(String name)
{
this
.name = name;
memberCount++;
FictionalCharacter
}