Java Reference
In-Depth Information
This kind of situation occurs frequently, so Java provides a construct, the
abstract class
, to handle it better. We use class
Shape
of Fig. 4.9 to illustrate. It
is written as an abstract class in Fig. 4.14. It differs from
Shape
of Fig. 4.9 in two
ways.
1. The class has been changed into an abstract class. This is done by insert-
ing keyword
abstract
before keyword
class
in the first line of the class
definition:
public abstract class
Shape {
An abstract class cannot be instantiated: expression
new
Shape(…)
is ille-
gal.
2. Method
drawShape
has been made into an
abstract method
. This is done
by inserting keyword
abstract
in the method definition and replacing
the body by a semicolon:
public abstract void
drawShape ( … );
An abstract method of an abstract class must be overridden in every sub-
class (unless the subclass is also abstract).
That is all there is to abstract classes and abstract methods: an abstract class
cannot be instantiated, and an abstract method must be overridden. With these
import
java.awt.*;
/**
A shape on a screen.
*/
public abstract class
Shape {
/**
Constructor: a shape that fits in a bounding rectangle with upper-left corner
(x, y) */
public
Shape (
int
x,
int
y){ }
/** =
x-coordinate of upper-left corner of bounding rectangle
*/
public int
getX()
{
return
0; }
/** =
x-coordinate of upper-left corner of bounding rectangle
*/
public int
getX()
{
return
0; }
/** =
a description of this shape, of the form
(
x-coordinate
,
y-coordinate
) */
public
String toString()
{
return
""; }
/**
Draw this shape using
g*/
public abstract void
drawShape(Graphics g);
}
Figure 4.14:
Design of class
Shape
as an abstract class, with abstract method
drawShape
Search WWH ::
Custom Search