Java Reference
In-Depth Information
2.4. Creating Objects
In this first version of Body , objects that represent particular celestial bod-
ies are created and initialized like this:
Body sun = new Body();
sun.idNum = Body.nextID++;
sun.name = "Sol";
sun.orbits = null; // in solar system, sun is middle
Body earth = new Body();
earth.idNum = Body.nextID++;
earth.name = "Earth";
earth.orbits = sun;
First we declare a reference variable ( sun ) that can refer to objects of
type Body . As mentioned before, such a declaration does not create an
object; it only defines a variable that references objects. The object it
refers to must be created explicitly.
We create the object sun refers to using new . The new construct is by far
the most common way to create objects (we cover the other ways in
Chapter 16 ). When you create an object with new , you specify the type
of object you want to create and any arguments for its construction. The
runtime system allocates enough space to store the fields of the object
and initializes it in ways you will soon see. When initialization is com-
plete, the runtime system returns a reference to the new object.
If the system cannot find enough free space to create the object, it may
have to run the garbage collector to try to reclaim space. If the system
still cannot find enough free space, new throws an OutOfMemoryError excep-
tion.
Having created a new Body object, we initialize its variables. Each Body ob-
ject needs a unique identifier, which it gets from the static nextID field of
 
Search WWH ::




Custom Search