Java Reference
In-Depth Information
void move(int dx, int dy) {
x += dx;
y += dy;
alert();
}
abstract void alert();
}
abstract class ColoredPoint extends Point {
int color;
}
class SimplePoint extends Point {
void alert() { }
}
Here, a class
Point
is declared that must be declared
abstract
, because it contains a de-
claration of an
abstract
method named
alert
. The subclass of
Point
named
ColoredPoint
in-
herits the
abstract
method
alert
, so it must also be declared
abstract
. On the other hand,
the subclass of
Point
named
SimplePoint
provides an implementation of
alert
, so it need
not be
abstract
.
The statement:
Point p = new Point();
would result in a compile-time error; the class
Point
cannot be instantiated because it
is
abstract
. However, a
Point
variable could correctly be initialized with a reference to
any subclass of
Point
, and the class
SimplePoint
is not
abstract
, so the statement:
Point p = new SimplePoint();
would be correct. Instantiation of a
SimplePoint
causes the default constructor and field
initializers for
x
and
y
of
Point
to be executed.
Example 8.1.1.1-2. Abstract Class Declaration that Prohibits Subclasses
interface Colorable {
void setColor(int color);
}
abstract class Colored implements Colorable {
public abstract int setColor(int color);
}
These declarations result in a compile-time error: it would be impossible for any sub-
class of class
Colored
to provide an implementation of a method named
setColor
, taking