Object: The Cosmic Superclass
The Object class is the ultimate ancestor—every class in Java extends Object. However, you never have to write
class Employee extends Object
The ultimate superclass Object is taken for granted if no superclass is explicitly mentioned. Because every class in Java extends Object, it is important to be familiar with the services provided by the Object class. We go over the basic ones in this chapter and refer you to later chapters or to the on-line documentation for what is not covered here. (Several methods of Object come up only when dealing with threads—see Volume II for more on threads.)
You can use a variable of type Object to refer to objects of any type:
Object obj = new Employee("Harry Hacker", 35000);
Of course, a variable of type Object is only useful as a generic holder for arbitrary values. To do anything specific with the value, you need to have some knowledge about the original type and then apply a cast:
Employee e = (Employee) obj;
In Java, only the primitive types (numbers, characters, and boolean values) are not objects.
All array types, no matter whether they are arrays of objects or arrays of primitive types, are class types that extend the Object class.
Employee[] staff = new Employee[10]; obj = staff; // OK obj = new int[10]; // OK
The equals Method
The equals method in the Object class tests whether one object is considered equal to another. The equals method, as implemented in the Object class, determines whether two object references are identical. This is a pretty reasonable default—if two objects are identical, they should certainly be equal. For quite a few classes, nothing else is required. For example, it makes little sense to compare two PrintStream objects for equality. However, you will often want to implement state-based equality testing, in which two objects are considered equal when they have the same state.
For example, let us consider two employees equal if they have the same name, salary, and hire date. (In an actual employee database, it would be more sensible to compare IDs instead. We use this example to demonstrate the mechanics of implementing the equals method.)
class Employee { . . . public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) return true; // must return false if the explicit parameter is null if (otherObject == null) return false; // if the classes don't match, they can't be equal if (getClass() != otherObject.getClass()) return false; // now we know otherObject is a non-null Employee Employee other = (Employee) otherObject; // test whether the fields have identical values return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay); } }
The getClass method returns the class of an object—we discuss this method in detail later in this chapter. In our test, two objects can only be equal when they belong to the same class.
When you define the equals method for a subclass, first call equals on the superclass. If that test doesn't pass, then the objects can't be equal. If the superclass fields are equal, then you are ready to compare the instance fields of the subclass.
class Manager extends Employee { . . . public boolean equals(Object otherObject) { if (!super.equals(otherObject)) return false; // super.equals checked that this and otherObject belong to the same class Manager other = (Manager) otherObject; return bonus == other.bonus; } }
Equality Testing and Inheritance
How should the equals method behave if the implicit and explicit parameters don't belong to the same class? This has been an area of some controversy. In the preceding example, the equals method returns false if the classes don't match exactly. But many programmers use an instanceof test instead:
if (!(otherObject instanceof Employee)) return false;
This leaves open the possibility that otherObject can belong to a subclass. However, this approach can get you into trouble. Here is why. The Java Language Specification requires that the equals method has the following properties:
- It is reflexive: For any non-null reference x, x.equals(x) should return true.
- It is symmetric: For any references x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: For any references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: If the objects to which x and y refer haven't changed, then repeated calls to x.equals(y) return the same value.
- For any non-null reference x, x.equals(null) should return false.
These rules are certainly reasonable. You wouldn't want a library implementor to ponder whether to call x.equals(y) or y.equals(x) when locating an element in a data structure.
However, the symmetry rule has subtle consequences when the parameters belong to different classes. Consider a call
e.equals(m)
where e is an Employee object and m is a Manager object, both of which happen to have the same name, salary, and hire date. If Employee.equals uses an instanceof test, the call returns true. But that means that the reverse call
m.equals(e)
also needs to return true—the symmetry rule does not allow it to return false or to throw an exception.
That leaves the Manager class in a bind. Its equals method must be willing to compare itself to any Employee, without taking manager-specific information into account! All of a sudden, the instanceof test looks less attractive!
Some authors have gone on record that the getClass test is wrong because it violates the substitution principle. A commonly cited example is the equals method in the AbstractSet class that tests whether two sets have the same elements. The AbstractSet class has two concrete subclasses, TreeSet and HashSet, that use different algorithms for locating set elements. You really want to be able to compare any two sets, no matter how they are implemented.
However, the set example is rather specialized. It would make sense to declare AbstractSet.equals as final, because nobody should redefine the semantics of set equality. (The method is not actually final. This allows a subclass to implement a more efficient algorithm for the equality test.)
The way we see it, there are two distinct scenarios:
- If subclasses can have their own notion of equality, then the symmetry requirement forces you to use the getClass test.
- If the notion of equality is fixed in the superclass, then you can use the instanceof test and allow objects of different subclasses to be equal to another.
In the example of the employees and managers, we consider two objects to be equal when they have matching fields. If we have two Manager objects with the same name, salary, and hire date, but with different bonuses, we want them to be different. Therefore, we used the getClass test.
But suppose we used an employee ID for equality testing. This notion of equality makes sense for all subclasses. Then we could use the instanceof test, and we should declare Employee.equals as final.
Here is a recipe for writing the perfect equals method:
- Name the explicit parameter otherObject—later, you need to cast it to another variable that you should call other.
- Test whether this happens to be identical to otherObject:
if (this == otherObject) return true;
This statement is just an optimization. In practice, this is a common case. It is much cheaper to check for identity than to compare the fields. - Test whether otherObject is null and return false if it is. This test is required.
if (otherObject == null) return false;
- Compare the classes of this and otherObject. If the semantics of equals can change in subclasses, use the getClass test:
if (getClass() != otherObject.getClass()) return false;
If the same semantics holds for all subclasses, you can use an instanceof test:if (!(otherObject instanceof ClassName)) return false;
- Cast otherObject to a variable of your class type:
ClassName other = (ClassName) otherObject
Now compare the fields, as required by your notion of equality. Use == for primitive type fields, equals for object fields. Return true if all fields match, false otherwise.
return field1 == other.field1 && field2.equals(other.field2) && . . .;
If you redefine equals in a subclass, include a call to super.equals(other).
The hashCode Method
A hash code is an integer that is derived from an object. Hash codes should be scrambled—if x and y are two distinct objects, there should be a high probability that x.hashCode() and y.hashCode() are different. Table 5-1 lists a few examples of hash codes that result from the hashCode method of the String class.
Table 5-1. Hash Codes Resulting from the hashCode Function
String |
Hash Code |
Hello |
69609650 |
Harry |
69496448 |
Hacker |
–2141031506 |
The String class uses the following algorithm to compute the hash code:
int hash = 0; for (int i = 0; i < length(); i++) hash = 31 * hash + charAt(i);
The hashCode method is defined in the Object class. Therefore, every object has a default hash code. That hash code is derived from the object's memory address. Consider this example:
String s = "Ok"; StringBuilder sb = new StringBuilder(s); System.out.println(s.hashCode() + " " + sb.hashCode()); String t = new String("Ok"); StringBuilder tb = new StringBuilder(t); System.out.println(t.hashCode() + " " + tb.hashCode());
Table 5-2 shows the result.
Table 5-2. Hash Codes of Strings and String Builders
Object |
Hash Code |
s |
2556 |
sb |
20526976 |
t |
2556 |
tb |
20527144 |
Note that the strings s and t have the same hash code because, for strings, the hash codes are derived from their contents. The string builders sb and tb have different hash codes because no hashCode method has been defined for the StringBuilder class, and the default hashCode method in the Object class derives the hash code from the object's memory address.
If you redefine the equals method, you will also need to redefine the hashCode method for objects that users might insert into a hash table. (We discuss hash tables in Chapter 2 of Volume II.)
The hashCode method should return an integer (which can be negative). Just combine the hash codes of the instance fields so that the hash codes for different objects are likely to be widely scattered.
For example, here is a hashCode method for the Employee class:
class Employee { public int hashCode() { return 7 * name.hashCode() + 11 * new Double(salary).hashCode() + 13 * hireDay.hashCode(); } . . . }
Your definitions of equals and hashCode must be compatible: if x.equals(y) is true, then x.hashCode() must be the same value as y.hashCode(). For example, if you define Employee.equals to compare employee IDs, then the hashCode method needs to hash the IDs, not employee names or memory addresses.
The toString Method
Another important method in Object is the toString method that returns a string representing the value of this object. Here is a typical example. The toString method of the Point class returns a string like this:
java.awt.Point[x=10,y=20]
Most (but not all) toString methods follow this format: the name of the class, followed by the field values enclosed in square brackets. Here is an implementation of the toString method for the Employee class:
public String toString() { return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; }
Actually, you can do a little better. Rather than hardwiring the class name into the toString method, call getClass().getName() to obtain a string with the class name.
public String toString() { return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; }
The toString method then also works for subclasses.
Of course, the subclass programmer should define its own toString method and add the subclass fields. If the superclass uses getClass().getName(), then the subclass can simply call super.toString(). For example, here is a toString method for the Manager class:
class Manager extends Employee { . . . public String toString() { return super.toString() + "[bonus=" + bonus + "]"; } }
Now a Manager object is printed as
Manager[name=...,salary=...,hireDay=...][bonus=...]
The toString method is ubiquitous for an important reason: whenever an object is concatenated with a string by the "+" operator, the Java compiler automatically invokes the toString method to obtain a string representation of the object. For example:
Point p = new Point(10, 20); String message = "The current position is " + p; // automatically invokes p.toString()
If x is any object and you call
System.out.println(x);
then the println method simply calls x.toString() and prints the resulting string.
The Object class defines the toString method to print the class name and the hash code of the object. For example, the call
System.out.println(System.out)
produces an output that looks like this:
java.io.PrintStream@2f6684
The reason is that the implementor of the PrintStream class didn't bother to override the toString method.
The toString method is a great tool for logging. Many classes in the standard class library define the toString method so that you can get useful information about the state of an object. This is particularly useful in logging messages like this:
System.out.println("Current position = " + position);
As we explain in Chapter 11, an even better solution is
Logger.global.info("Current position = " + position);
The program in Listing 5-3 implements the equals, hashCode, and toString methods for the Employee and Manager classes.
Listing 5-3. EqualsTest.java
1. import java.util.*; 2. 3. /** 4. * This program demonstrates the equals method. 5. * @version 1.11 2004-02-21 6. * @author Cay Horstmann 7. */ 8. public class EqualsTest 9. { 10. public static void main(String[] args) 11. { 12. Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15); 13. Employee alice2 = alice1; 14. Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15); 15. Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1); 16. 17. System.out.println("alice1 == alice2: " + (alice1 == alice2)); 18. 19. System.out.println("alice1 == alice3: " + (alice1 == alice3)); 20. 21. System.out.println("alice1.equals(alice3): " + alice1.equals(alice3)); 22. 23. System.out.println("alice1.equals(bob): " + alice1.equals(bob)); 24. 25. System.out.println("bob.toString(): " + bob); 26. 27. Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15); 28. Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); 29. boss.setBonus(5000); 30. System.out.println("boss.toString(): " + boss); 31. System.out.println("carl.equals(boss): " + carl.equals(boss)); 32. System.out.println("alice1.hashCode(): " + alice1.hashCode()); 33. System.out.println("alice3.hashCode(): " + alice3.hashCode()); 34. System.out.println("bob.hashCode(): " + bob.hashCode()); 35. System.out.println("carl.hashCode(): " + carl.hashCode()); 36. } 37. } 38. 39. class Employee 40. { 41. public Employee(String n, double s, int year, int month, int day) 42. { 43. name = n; 44. salary = s; 45. GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); 46. hireDay = calendar.getTime(); 47. } 48. 49. public String getName() 50. { 51. return name; 52. } 53. 54. public double getSalary() 55. { 56. return salary; 57. } 58. 59. public Date getHireDay() 60. { 61. return hireDay; 62. } 63. 64. public void raiseSalary(double byPercent) 65. { 66. double raise = salary * byPercent / 100; 67. salary += raise; 68. } 69. 70. public boolean equals(Object otherObject) 71. { 72. // a quick test to see if the objects are identical 73. if (this == otherObject) return true; 74. 75. // must return false if the explicit parameter is null 76. if (otherObject == null) return false; 77. 78. // if the classes don't match, they can't be equal 79. if (getClass() != otherObject.getClass()) return false; 80. 81. // now we know otherObject is a non-null Employee 82. Employee other = (Employee) otherObject; 83. 84. // test whether the fields have identical values 85. return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay); 86. } 87. 88. public int hashCode() 89. { 90. return 7 * name.hashCode() + 11 * new Double(salary).hashCode() + 13 * hireDay.hashCode(); 91. } 92. 93. public String toString() 94. { 95. return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay 96. + "]"; 97. } 98. 99. private String name; 100. private double salary; 101. private Date hireDay; 102. } 103. 104. class Manager extends Employee 105. { 106. public Manager(String n, double s, int year, int month, int day) 107. { 108. super(n, s, year, month, day); 109. bonus = 0; 110. } 111. 112. public double getSalary() 113. { 114. double baseSalary = super.getSalary(); 115. return baseSalary + bonus; 116. } 117. 118. 119. public void setBonus(double b) 120. { 121. bonus = b; 122. } 123. 124. public boolean equals(Object otherObject) 125. { 126. if (!super.equals(otherObject)) return false; 127. Manager other = (Manager) otherObject; 128. // super.equals checked that this and other belong to the same class 129. return bonus == other.bonus; 130. } 131. 132. public int hashCode() 133. { 134. return super.hashCode() + 17 * new Double(bonus).hashCode(); 135. } 136. 137. public String toString() 138. { 139. return super.toString() + "[bonus=" + bonus + "]"; 140. } 141. 142. private double bonus; 143. }