Java Reference
In-Depth Information
Both
minivan
and
sportscar
are initialized by the
Vehicle( )
constructor when they are
created. Each object is initialized as specified in the parameters to its constructor. For ex-
ample, in the following line,
the values 7, 16, and 21 are passed to the
Vehicle( )
constructor when
new
creates the ob-
ject. Thus,
minivan
's copy of
passengers
,
fuelcap
, and
mpg
will contain the values 7, 16,
and 21, respectively. The output from this program is the same as the previous version.
The new Operator Revisited
Now that you know more about classes and their constructors, let's take a closer look at the
new
operator. In the context of an assignment, the
new
operator has this general form:
class-var
= new
class-name(arg-list);
Here,
class-var
is a variable of the class type being created. The
class-name
is the name of
the class that is being instantiated. The class name followed by a parenthesized argument
list (which can be empty) specifies the constructor for the class. If a class does not define
its own constructor,
new
will use the default constructor supplied by Java. Thus,
new
can
be used to create an object of any class type. The
new
operator returns a reference to the
newly created object, which (in this case) is assigned to
class-var
.
Since memory is finite, it is possible that
new
will not be able to allocate memory for an
object because insufficient memory exists. If this happens, a run-time exception will occur.
(You will learn about exceptions in
Chapter 9
.) For the sample programs in this topic, you
won't need to worry about running out of memory, but you will need to consider this pos-
sibility in real-world programs that you write.
Garbage Collection
As you have seen, objects are dynamically allocated from a pool of free memory by using
the
new
operator. As explained, memory is not infinite, and the free memory can be ex-
hausted. Thus, it is possible for
new
to fail because there is insufficient free memory to cre-
ate the desired object. For this reason, a key component of any dynamic allocation scheme
is the recovery of free memory from unused objects, making that memory available for sub-
sequent reallocation. In some programming languages, the release of previously allocated
memory is handled manually. However, Java uses a different, more trouble-free approach:
garbage collection
.