Java Reference
In-Depth Information
Creating and Initializing Objects
Now that we've covered fields and methods, let's move on to other important mem‐
bers of a class. In particular, we'll look at constructors—these are class members
whose job is to initialize the fields of a class as new instances of the class are created.
Take another look at how we've been creating
Circle
objects:
Circle
c
=
new
Circle
();
This can easily be read as the creation of a new instance of
Circle
, by calling some‐
thing that looks a bit like a method. In fact,
Circle()
is an example of a
constructor
.
This is a member of a class that has the same name as the class, and has a body, like
a method.
Here's how a constructor works. The
new
operator indicates that we need to create a
new instance of the class. First of all, memory is allocated to hold the new object
instance. Then, the constructor body is called, with any arguments that have been
specified. The constructor uses these arguments to do whatever initialization of the
new object is necessary.
Every class in Java has at least one
constructor
, and their purpose is to perform any
necessary initialization for a new object. Because we didn't explicitly define a con‐
structor for our
Circle
class in
Example 3-1
, the javac compiler automatically gave
us a constructor (called the default constructor) that takes no arguments and per‐
forms no special initialization.
Deining a Constructor
There is some obvious initialization we could do for our circle objects, so let's define
a constructor.
Example 3-2
shows a new definition for
Circle
that contains a con‐
structor that lets us specify the radius of a new
Circle
object. We've also taken the
opportunity to make the field
r
protected (to prevent access to it from arbitary
objects).
Example 3-2. A constructor for the Circle class
public
class
Circle
{
public
static
final
double
PI
=
3.14159
;
// A constant
// An instance field that holds the radius of the circle
protected
double
r
;
// The constructor: initialize the radius field
public
Circle
(
double
r
)
{
this
.
r
=
r
;
}
// The instance methods: compute values based on the radius
public
double
circumference
()
{
return
2
*
PI
*
r
;
}
public
double
area
()
{
return
PI
*
r
*
r
;
}
public
double
radius
()
{
return
r
;
}
}