Java Reference
In-Depth Information
The output produced by this program is shown here:
As you can see,
minivan
's data is completely separate from the data contained in
sports-
car
. The following illustration depicts this situation.
How Objects Are Created
In the preceding programs, the following line was used to declare an object of type
Vehicle
:
This declaration performs two functions. First, it declares a variable called
minivan
of the
class type
Vehicle
. This variable does not define an object. Instead, it is simply a variable
that can
refer to
an object. Second, the declaration creates a physical copy of the object and
assigns to
minivan
a reference to that object. This is done by using the
new
operator.
The
new
operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it. This reference is, more or less, the address in memory
of the object allocated by
new
. This reference is then stored in a variable. Thus, in Java, all
class objects must be dynamically allocated.
The two steps combined in the preceding statement can be rewritten like this to show
each step individually: