Java Reference
In-Depth Information
hr 12
min 35
sec 48
hr 12
min 27
sec 15
myClock
yourClock
equals
otherClock
FIGURE 8-10
Object
myClock
and parameter
otherClock
Note that
otherClock
and
yourClock
refer to the same object. The instance variables
hr
,
min
, and
sec
of the object
otherClock
have the values
12
,
27
, and
15
, respectively.
In other words, when the body of the method
equals
executes, the value of
otherClock.hr
is
12
, the value of
otherClock.min
is
27
, and the value of
otherClock.sec
is
15
. The method
equals
is a member of
myClock
. When the
method
equals
executes, the variables
hr
,
min
, and
sec
in the body of the method
equals
are the instance variables of the object
myClock
. Therefore, the instance variable
hr
of the object
myClock
is compared with
otherClock.hr
, the instance variable
min
of the object
myClock
is compared with
otherClock.min
, and the instance variable
sec
of the object
myClock
is compared with
otherClock.sec
.
Once again, in the expression:
8
myClock.equals(yourClock)
the method
equals
is invoked by
myClock
and compares the object
myClock
with the
object
yourClock
. It follows that the method
equals
needs only one parameter.
Let us again take a look at the definition of the method
equals
. Notice that within the
definition of this method, the object
otherClock
accesses the data members
hr
,
min
,
and
sec
. However, these data members are
private
. So is there any violation? The
answer is no. The method
equals
is a member of the
class
Clock
and
hr
,
min
, and
sec
are the data members. Moreover,
otherClock
is an object of the
class
Clock
.
Therefore, the object
otherClock
can access its
private
data members within the
definition of the method
equals
. The same is true for any method of a class.
That is, in general, when you write the definition of a method, say,
dummyMethod
,ofa
class
, say,
DummyClass
, and the method uses an object,
dummyObject
of the
class
DummyClass
, then within the definition of
dummyMethod
the object
dummyObject
can
access its
private
data members (in fact, any
private
member of the class).
The method
makeCopy
copies the instance variables of its parameter,
otherClock
, into
the corresponding instance variables of the object referenced by the variable using this
method. Its definition is:
Search WWH ::
Custom Search