Page 544 - Introduction to Programming with Java: A Problem Solving Approach
P. 544
510 Chapter 13 Inheritance and Polymorphism 13.3 The equals Method
Syntax
The Object class’s equals method—which is inherited automatically by all other classes—has this pub- lic interface:
public boolean equals(Object obj)
Because all classes automatically inherit this method, unless a similarly defined method takes precedence, any object, objectA, can invoke this method to compare itself with any other object, objectB, with a method call like this:
objectA.equals(objectB)
This method call returns a boolean value of either true or false. Notice that we did not specify the type of either objectA or objectB. In general, they can be instantiations of any class, and they do not need to be objects of the same class. The only constraint is that objectA must be a non-null reference. For example, if Cat and Dog classes exist, this code works correctly:
Cat cat = new Cat();
Dog dog = new Dog();
System.out.println(cat.equals(dog));
Output:
false
Apago PDF Enhancer
The equals method that is called here is the equals method which the Cat class automatically inherits from the Object class. The parameter in this inherited method is of type Object, as specified in the method’s public interface above. But the dog argument we pass to this method is not of type Object. It is of type Dog. So what’s happening? When we pass the dog reference into the inherited equals method, the reference type automatically promotes from type Dog to type Object. Then the inherited equals method performs an internal test to see if the passed in dog is the same as the calling cat. Of course it is not, so the output is false, as you can see.
Semantics
Notice that we just said, “performs an internal test.” Now let’s focus on that mysterious “internal test.” How can you tell if two objects are the same or “equal”? When you say “objectA equals objectB,” you could mean this:
1. objectA is just an alias for objectB, and both objectA and objectB refer to exactly the same object.
Or you could mean this:
2. objectA and objectB are two separate objects which have the same attributes.
The equals method that all classes inherit from the Object class implements the narrowest possible meaning of the word “equals.” That is, this method returns true if and only if objectA and objectB refer to exactly the same object (definition 1. above). This meaning of “equals” is exactly the same as the