Java Reference
In-Depth Information
double
delta_x
=
(
Circle
.
PI
/
2
)/(
NUMPTS
-
1
);
for
(
int
i
=
0
,
x
=
0.0
;
i
<
NUMPTS
;
i
++,
x
+=
delta_x
)
{
sines
[
i
]
=
Math
.
sin
(
x
);
cosines
[
i
]
=
Math
.
cos
(
x
);
}
}
// The rest of the class is omitted...
}
A class can have any number of static initializers. The body of each initializer block
is incorporated into the class initialization method, along with any static field initi‐
alization expressions. A static initializer is like a class method in that it cannot use
the
this
keyword or any instance fields or instance methods of the class.
Classes are also allowed to have
instance initializers
. An instance initializer is like a
static initializer, except that it initializes an object, not a class. A class can have any
number of instance initializers, and they can appear anywhere a field or method
definition can appear. The body of each instance initializer is inserted at the begin‐
ning of every constructor for the class, along with any field initialization expres‐
sions. An instance initializer looks just like a static initializer, except that it doesn't
use the
static
keyword. In other words, an instance initializer is just a block of
arbitrary Java code that appears within curly braces.
Instance initializers can initialize arrays or other fields that require complex initiali‐
zation. They are sometimes useful because they locate the initialization code right
next to the field, instead of separating into a constructor. For example:
private
static
final
int
NUMPTS
=
100
;
private
int
[]
data
=
new
int
[
NUMPTS
];
{
for
(
int
i
=
0
;
i
<
NUMPTS
;
i
++)
data
[
i
]
=
i
;
}
In practice, however, this use of instance initializers is fairly rare.
Subclasses and Inheritance
The
Circle
defined earlier is a simple class that distinguishes circle objects only by
their radii. Suppose, instead, that we want to represent circles that have both a size
and a position. For example, a circle of radius 1.0 centered at point 0,0 in the Carte‐
sian plane is different from the circle of radius 1.0 centered at point 1,2. To do this,
we need a new class, which we'll call
PlaneCircle
.
We'd like to add the ability to represent the position of a circle without losing any of
the existing functionality of the
Circle
class. This is done by defining
PlaneCircle
as a subclass of
Circle
so that
PlaneCircle
inherits the fields and methods of its
superclass,
Circle
. The ability to add functionality to a class by subclassing, or
extending, is central to the object-oriented programming paradigm.