Java Reference
In-Depth Information
figure 4.46
An illustration of
overloading equals
instead of overriding
equals . Here, the call
to the sameVal returns
false!
1 final class SomeClass
2 {
3 public SomeClass( int i )
4 { id = i; }
5
6 public boolean sameVal( Object other )
7 { return other instanceof SomeClass && equals( other ); }
8
9 /**
10 * This is a bad implementation!
11 * other has the wrong type, so this does
12 * not override Object's equals.
13 */
14 public boolean equals( SomeClass other )
15 { return other != null && id == other.id; }
16
17 private int id;
18 }
19
20 class BadEqualsDemo
21 {
22 public static void main( String [ ] args )
23 {
24 SomeClass obj1 = new SomeClass( 4 );
25 SomeClass obj2 = new SomeClass( 4 );
26
27 System.out.println( obj1.equals( obj2 ) ); // true
28 System.out.println( obj1.sameVal( obj2 ) ); // false
29 }
30 }
The problem is that the call in sameVal is this.equals(other) . The static
type of this is SomeClass . In SomeClass , there are two versions of equals : the
listed equals that takes a SomeClass as a parameter, and the inherited equals
that takes an Object . The static type of the parameter ( other ) is Object , so
the best match is the equals that takes an Object . At run time, the virtual
machine searches for that equals , and finds the one in class Object . And
since this and other are different objects, the equals method in class Object
returns false.
Thus, equals must be written to take an Object as a parameter, and typi-
cally a downcast will be required after a verification that the type is appropri-
ate. One way of doing that is to use an instanceof test, but that is safe only for
final classes. Overriding equals is actually fairly tricky in the presence of
inheritance, and is discussed in Section 6.7.
Search WWH ::




Custom Search