Java Reference
In-Depth Information
Creating Objects of a Class
When you declare a variable of type Sphere with the statement:
Sphere ball; // Declare a variable
no constructor is called and no object is created. All you have created at this point is the variable ball ,
which can store a reference to an object of type Sphere , if and when you create one.
ball=new Sphere(10.0,1.0,1.0,1.0);
Sphere ball;
creates a
object in
creates a memory location
to hold a reference to an
object of type
Sphere
ball
memory and sets
to
.
Sphere
reference it.
ball
radius
xCenter
yCenter
zCenter
10.0
1.0
1.0
1.0
No object is created and no
memory is allocated for an
object.
You will recall from our discussion of String objects and arrays that the variable and the object it
references are distinct entities. To create an object of a class you must use the keyword new followed by
a call to a constructor. To initialize ball with an object, you could write:
ball = new Sphere(10.0, 1.0, 1.0, 1.0); // Create a sphere
Now we have a Sphere object with a radius of 10.0 located at the coordinates (1.0, 1.0, 1.0). The object
is created in memory and will occupy a sufficient number of bytes to accommodate all the data
necessary to define the object. The variable ball will record where in memory the object is - it acts as
a reference to the object.
Of course, you can do the whole thing in one step, with the statement:
Sphere ball = new Sphere(10.0, 1.0, 1.0, 1.0); // Create a sphere
This declares the variable ball and defines the Sphere object to which it refers.
You can create another variable that refers to the same object as ball :
Sphere myBall = ball;
Now the variable myBall refers to the same object as ball . We have only one object still, but we have
two different variables that reference it. You could have as many variables as you like referring to the
same object.
The separation of the variable and the object has an important effect on how objects are passed to a
method, so we need to look at that.
Search WWH ::




Custom Search