Java Reference
In-Depth Information
That is, the preceding statement declares
yourClock
to be a reference variable of type
Clock
and instantiates the object
yourClock
to store the hours, minutes, and seconds.
The instance variables
hr
,
min
, and
sec
of the object
yourClock
are initialized to
9
,
35
,
and
15
, respectively, by the constructor with parameters.
When we use phrases such as ''create an object of a
class
type'' we mean to: (i) declare
a reference variable of the
class
type, (ii) instantiate the
class
object, and
(iii) store the address of the object into the reference variable declared. For example,
the following statements create the object
tempClock
of the
Clock
type:
Clock tempClock =
new
Clock();
The object
tempClock
is accessed via the reference variable
tempClock
.
Recall from Chapter 3 that a
class
object is called an instance of that
class
.
Once an object of a class is created, the object can access the members (as explained in the
next paragraph, after the syntax) of the
class
. The general syntax for an object to access a
data member or a method is:
8
referenceVariableName.memberName
The class members that the class object can access depend on where the object is created.
If the object is created in the definition of a method of the class, then the
object can access both the
public
and
private
members. We will
elaborate on this when we write the definitions of the methods
equals
,
makeCopy
, and
getCopy
of the
class
Clock
later in this chapter.
If the object is created elsewhere (for example, in a user's program), then
the object can access only the
public
members of the class.
Recall that in Java, the dot
.
(period) is called the member access operator.
Example 8-1 illustrates how to access the members of a class.
EXAMPLE 8-1
Suppose that the objects
myClock
and
yourClock
have been created as before. Consider
the following statements:
myClock.setTime(5, 2, 30);
myClock.printTime();
yourClock.setTime(x, y, z);
//Assume x, y, and z are variables
//of type int that have been
//initialized.
Search WWH ::
Custom Search