Java Reference
In-Depth Information
if (myClock.equals(yourClock))
.
.
.
These statements are legal; that is, they are syntactically correct. Note the following:
￿ In the first statement, myClock.setTime(5, 2, 30); ,themethod
setTime is executed. The values 5 , 2 ,and 30 are passed as parameters
to the method setTime , and the method uses these values to set the
values of hr , min ,and sec of the object myClock to 5 , 2 ,and 30 ,
respectively.
￿ Similarly, the second statement executes the method printTime and
outputs the values of hr , min , and sec of the object myClock .
￿ In the third statement, the values of the variables x , y , and z are used to
set the values of hr , min , and sec of the object yourClock .
￿ In the fourth statement, the method equals executes and compares the
instance variables of the object myClock with the corresponding instance
variables of the object yourClock . Because in this statement the method
equals is invoked by the variable myClock , it has direct access to the
instance variables of the object myClock . So it needs one more object to
compare, which, in this case, is the object yourClock . This explains why
the method equals has only one parameter.
The objects myClock and yourClock can access only public members of the class. The
following statements are illegal because hr and min are private members of the class
Clock and, therefore, cannot be accessed by myClock and yourClock :
myClock.hr = 10;
//illegal
myClock.min = yourClock.min;
//illegal
Built-in Operations on Classes
Most of Java's built-in operations do not apply to classes. You cannot perform arithmetic
operations on class objects. For example, you cannot use the operator + to add the values
of two Clock objects. Also, you cannot use relational operators to compare two class
objects in any meaningful way.
The built-in operation that is valid for classes is the dot operator ( . ). A reference variable
uses the dot operator to access public members; classes can use the dot operator to access
public static members.
Assignment Operator and Classes: A Precaution
This section discusses how the assignment operator works with reference variables and
objects.
 
Search WWH ::




Custom Search