Java Reference
In-Depth Information
An abstract method does not have a body. The
abstract
keyword must be used
to define an abstract method. An abstract method can be only part of an abstract
class. Any non-abstract class must
override
all abstract methods of the superclass and
include the bodies for the methods. Overriding a method means including a method
with the same signature in the subclass.
Here is the new version of the
FictionalCharacter
class.
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;
public abstract double
computeStrength() ;
}
Note that an abstract class does not need to contain an abstract method. However,
an abstract method can only be defined as part of an abstract class. For example, if the
FictionalCharacter
class was not abstract, then the following code will be ambiguous.
FictionalCharacter fc1 =
new
FictionalCharacter(
"Superman"
);
System. out . println ( fc1 . computeStrength() ) ;
The problem is that the implementation of the
computeStrength
method is miss-
ing inside the
FictionalCharacter
class. That is, the method can only be invoked on
an object that belongs to a subclass of the
FictionalCharacter
class. By defining the
FictionalCharacter
class abstract, we can guarantee that the class will only be in-
stantiated from subclasses of the
FictionalCharacter
classes and therefore calling the
computeStrength
method will be meaningful.
8.6 Auto-casting, Polymorphism, and Dynamic Binding
Let us now examine an implementation of the
Superhero
and
Villain
classes. In each
class, the strength of the fictional character is computed differently.
public class
Superhero
extends
FictionalCharacter
{
private int
goodPower ;
private int
respect ;
public
Superhero(String name,
int
goodPower ,
int
respect)
{
super
(name) ;
this
. goodPower = goodPower ;
this
. respect = respect ;