Java Reference
In-Depth Information
PITFALL: (continued)
Even though these two variables name objects that are intuitively equal, they are
stored in two different locations in the computer's memory. This is why you usually
use an equals method to compare objects of a class type. The variables variable1
and variable2 would be considered “equal” if compared using the equals method as
defined for the class ToyClass2 ( Display 5.17 ) .
Display 5.17 A Toy Class to Use in Display 5.16
1 public class ToyClass2
2{
3
private String name;
4
private int number;
5
public void set(String newName, int newNumber)
6
{
7
name = newName;
8
number = newNumber;
9
}
10
public String toString()
11
{
12
return (name + " " + number);
13
}
14
public void makeEqual(ToyClass2 anObject)
15
{
16
anObject.name = this .name;
Read the text for a discussion of
the problem with this method.
17
anObject.number = this .number;
18
}
19
public void tryToMakeEqual( int aNumber)
20
{
21
aNumber = this .number;
22
}
23
public boolean equals(ToyClass2 otherObject)
24
{
25
return ( (name.equals(otherObject.name))
26
&& (number == otherObject.number) );
27
}
<Other methods can be the same as in Display 5.11, although no
other methods are needed or used in the current discussion.>
28
}
 
Search WWH ::




Custom Search