Page 547 - Introduction to Programming with Java: A Problem Solving Approach
P. 547
the return statement returns false. Returning false is appropriate because a null otherCar is clearly not the same as the calling object Car.
Get in the habit of writing equals methods for most of your programmer-defined classes. Writing equals methods is usually straightforward since they tend to look the same. Feel free to use the Car class’s equals method as a template.
Remember that any reference variable can call the equals method. even if the reference variable’s class doesn’t define an equals method. You know what happens in that case, right? When the JVM real- izes that there’s no local equals method, it looks for the equals method in an ancestor class. If it doesn’t find an equals method prior to reaching the Object class at the top of the tree, it uses the Object class’s equals method. This default operation often appears as a bug. To fix the bug, make sure that your classes implement their own equals methods.
equals Methods in API Classes
Note that equals methods are built into many API classes.1 For example, the String class and the wrap- per classes implement equals methods. As you’d expect, these equals methods test whether two refer- ences point to data that is identical (not whether two references point to the same object).
You’ve seen the String class’s equals method before, so the following example should be fairly straightforward. It illustrates the difference between the == operator and the String class’s equals method. What does this code fragment print?
String s1 = "hello";
String s2 = "he";
s2 += "llo";
if (s1 == s2)
{
}
}
Apago PDF Enhancer
System.out.println("same object");
if (s1.equals(s2))
{
System.out.println("same contents");
The above code fragment prints “same contents.” Let’s make sure you understand why. The == operator returns true only if the two reference variables being compared refer to the same object. In the first if statement,s1 == s2returnsfalsesinces1ands2donotrefertothesameobject.Inthesecondif statement, s1.equals(s2) returns true since the characters in the two compared strings are the same.
Actually, there’s another twist to the String class. To minimize storage requirements, the Java com- piler makes String references refer to the same String object whenever an assignment refers to a duplicate string literal, That’s called string pooling. For example, suppose the above code included a third declaration that looked like this:
String s3 = "hello";
Then, if the if condition were (s1 == s3), the output would say “same object,” because s1 and s3 would refer to the same “hello” string object.
1 To get an idea of how common equals methods are, go to Sun’s Java API Web site (http://java.sun.com/javase/6/docs/api/) and search for all occurrences of equals.
13.3 The equals Method 513