Core Java(TM) 2, Volume I--Fundamentals (7th Edition) (Core Series) (Core Series)
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 2 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 C++ NOTE
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:
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, in the same order. 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.
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:
NOTE
CAUTION
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.
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"; StringBuffer sb = new StringBuffer(s); System.out.println(s.hashCode() + " " + sb.hashCode()); String t = new String("Ok"); StringBuffer tb = new StringBuffer(t); System.out.println(t.hashCode() + " " + tb.hashCode()); Table 5-2 shows the result.
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 buffers sb and tb have different hash codes because no hashCode method has been defined for the StringBuffer 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 2.) 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. java.lang.Object 1.0
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() TIP
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);
TIP
The program in Example 5-3 implements the equals, hashCode, and toString methods for the Employee and Manager classes. Example 5-3. EqualsTest.java
1. import java.util.*; 2. 3. public class EqualsTest 4. { 5. public static void main(String[] args) 6. { 7. Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15); 8. Employee alice2 = alice1; 9. Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15); 10. Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1); 11. 12. System.out.println("alice1 == alice2: " + (alice1 == alice2)); 13. 14. System.out.println("alice1 == alice3: " + (alice1 == alice3)); 15. 16. System.out.println("alice1.equals(alice3): " + alice1.equals(alice3)); 17. 18. System.out.println("alice1.equals(bob): " + alice1.equals(bob)); 19. 20. System.out.println("bob.toString(): " + bob); 21. 22. Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15); 23. Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); 24. boss.setBonus(5000); 25. System.out.println("boss.toString(): " + boss); 26. System.out.println("carl.equals(boss): " + carl.equals(boss)); 27. System.out.println("alice1.hashCode(): " + alice1.hashCode()); 28. System.out.println("alice3.hashCode(): " + alice3.hashCode()); 29. System.out.println("bob.hashCode(): " + bob.hashCode()); 30. System.out.println("carl.hashCode(): " + carl.hashCode()); 31. } 32. } 33. 34. class Employee 35. { 36. public Employee(String n, double s, 37. int year, int month, int day) 38. { 39. name = n; 40. salary = s; 41. GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); 42. hireDay = calendar.getTime(); 43. } 44. 45. public String getName() 46. { 47. return name; 48. } 49. 50. public double getSalary() 51. { 52. return salary; 53. } 54. 55. public Date getHireDay() 56. { 57. return hireDay; 58. } 59. 60. public void raiseSalary(double byPercent) 61. { 62. double raise = salary * byPercent / 100; 63. salary += raise; 64. } 65. 66. public boolean equals(Object otherObject) 67. { 68. // a quick test to see if the objects are identical 69. if (this == otherObject) return true; 70. 71. // must return false if the explicit parameter is null 72. if (otherObject == null) return false; 73. 74. // if the classes don't match, they can't be equal 75. if (getClass() != otherObject.getClass()) 76. return false; 77. 78. // now we know otherObject is a non-null Employee 79. Employee other = (Employee) otherObject; 80. 81. // test whether the fields have identical values 82. return name.equals(other.name) 83. && salary == other.salary 84. && hireDay.equals(other.hireDay); 85. } 86. 87. public int hashCode() 88. { 89. return 7 * name.hashCode() 90. + 11 * new Double(salary).hashCode() 91. + 13 * hireDay.hashCode(); 92. } 93. 94. public String toString() 95. { 96. return getClass().getName() 97. + "[name=" + name 98. + ",salary=" + salary 99. + ",hireDay=" + hireDay 100. + "]"; 101. } 102. 103. private String name; 104. private double salary; 105. private Date hireDay; 106. } 107. 108. class Manager extends Employee 109. { 110. public Manager(String n, double s, 111. int year, int month, int day) 112. { 113. super(n, s, year, month, day); 114. bonus = 0; 115. } 116. 117. public double getSalary() 118. { 119. double baseSalary = super.getSalary(); 120. return baseSalary + bonus; 121. } 122. 123. public void setBonus(double b) 124. { 125. bonus = b; 126. } 127. 128. public boolean equals(Object otherObject) 129. { 130. if (!super.equals(otherObject)) return false; 131. Manager other = (Manager) otherObject; 132. // super.equals checked that this and other belong to the 133. // same class 134. return bonus == other.bonus; 135. } 136. 137. public int hashCode() 138. { 139. return super.hashCode() 140. + 17 * new Double(bonus).hashCode(); 141. } 142. 143. public String toString() 144. { 145. return super.toString() 146. + "[bonus=" + bonus 147. + "]"; 148. } 149. 150. private double bonus; 151. } java.lang.Object 1.0
NOTE
java.lang.Class 1.0
|