Java Reference
In-Depth Information
} ...
}
8.5 Abstract Classes and Methods
Letusreexaminethe FictionalCharacter class. It stores the name of the fictional
character. Maybe we do not want anyone to be able to directly create fictional characters.
In other words, let us suppose that the only reason the class exists is so that we can inherit
from it and create the subclasses Superhero and Villain . In this case, we can make the
class abstract .
An abstract class is similar to a regular class. It can contain variables, methods,
and even constructors. However, an object cannot be directly instantiated from it. An
object of an abstract class can only be instantiated from a subclass using the super
keyword.
Here is a rewrite of the FictionalCharacter class using the abstract keyword.
public abstract class FictionalCharacter
{
private String name;
public FictionalCharacter ()
{
} public FictionalCharacter(String name) {
this .name = name;
}
public String getName () {
return name ;
} public void setName( String name) {
this .name = name;
}
}
We will add one more method to the FictionalCharacter class: computeStrength .The
method computes the strength of a fictional character. We assume that we can compute the
strength of any fictional character. However, the FictionalCharacter class does not store
enough information to compute this value. In other words, we will have this information
in every subclass of the FictionalCharacter class, but not in the class itself. Therefore,
we want to force every class that inherits from the FictionalCharacter class to redefine
the computeStrength method and include proper implementation. The computeStrength
method inside the FictionalCharacter class will not have a body and the method will be
defined as abstract .
 
Search WWH ::




Custom Search