Java Reference
In-Depth Information
Sphere ball; // Declare a variable
no constructor is called because 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.
Figure 5-5
shows this.
Recall from the 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 con-
structor. To initialize
ball
with a reference to an object, you could write:
ball = new Sphere(10.0, 1.0, 1.0, 1.0); // Create a sphere
Now you 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 occupies a sufficient number of bytes to accommodate all the data necessary to
define the object. The variable
ball
records where in memory the object is — it acts as a reference to the
object. This is illustrated in
Figure 5-5
.
Of course, you can do the whole thing in one step with the following 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
. You still have only one object, but you have
two different variables that reference it. You could have as many variables as you like referring to the same
object.
As I mentioned earlier, the separation of the variable and the object has an important effect on how ob-
jects are passed to a method, so let's look at that in more detail.
Passing Objects to a Method