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

In C++, there is no cosmic root class. However, every pointer can be converted to a void* pointer.

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:

  1. It is reflexive: for any non-null reference x, x.equals(x) should return true.

  2. It is symmetric: for any references x and y, x.equals(y) should return TRue if and only if y.equals(x) returns true.

  3. 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.

  4. 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.

  5. 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, 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.

  • 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:

  1. Name the explicit parameter otherObject later, you need to cast it to another variable that you should call other.

  2. 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.

  3. 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;

  4. Cast otherObject to a variable of your class type:

    ClassName other = (ClassName) otherObject

  5. 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).

NOTE

The standard Java library contains over 150 implementations of equals methods, with a mishmash of using instanceof, calling getClass, catching a ClassCastException, or doing nothing at all. Judging from this evidence, it does not appear as if all programmers have a clear understanding of the subtleties of the equals method. For example, Rectangle is a subclass of Rectangle2D. Both classes define an equals method with an instanceof test. Comparing a Rectangle2D with a Rectangle that has the same coordinates yields true, flipping the parameters yields false.

CAUTION

Here is a common mistake when implementing the equals method. Can you spot the problem?

public class Employee { public boolean equals(Employee other) { return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay); } ... }

This method declares the explicit parameter type as Employee. As a result, it does not override the equals method of the Object class but defines a completely unrelated method.

Starting with JDK 5.0, you can protect yourself against this type of error by tagging methods that are intended to override superclass methods with @Override:

@Override public boolean equals(Object other)

If you made a mistake and you are defining a new method, the compiler reports an error. For example, suppose you add the following declaration to the Employee class.

@Override public boolean equals(Employee other)

An error is reported because this method doesn't override any method from the Object superclass.

The @Override tag is a metadata tag. The metadata mechanism is very general and extensible, allowing compilers and tools to carry out arbitrary actions. Time will tell whether tool builders take advantage of this mechanism. In JDK 5.0, the compiler implementors decided to blaze the trail with the @Override tag.

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

140207504

Harry

140013338

Hacker

884756206

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.

Table 5-2. Hash Codes of Strings and String Buffers

Object

Hash Code

s

3030

sb

20526976

t

3030

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 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

  • int hashCode()

    returns a hash code for this object. A hash code can be any integer, positive or negative. Equal objects need to return identical hash codes.

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

Instead of writing x.toString(), you can write "" + x. This statement concatenates the empty string with the string representation of x that is exactly x.toString(). Unlike toString, this statement even works if x is of primitive type.

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

We strongly recommend that you add a toString method to each class that you write. You, as well as other programmers who use your classes, will be grateful for the logging support.

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

  • Class getClass()

    returns a class object that contains information about the object. As you see later in this chapter, Java has a runtime representation for classes that is encapsulated in the Class class.

  • boolean equals(Object otherObject)

    compares two objects for equality; returns TRue if the objects point to the same area of memory, and false otherwise. You should override this method in your own classes.

  • String toString()

    returns a string that represents the value of this object. You should override this method in your own classes.

  • Object clone()

    creates a clone of the object. The Java runtime system allocates memory for the new instance and copies the memory allocated for the current object.

NOTE

Cloning an object is important, but it also turns out to be a fairly subtle process filled with potential pitfalls for the unwary. We will have a lot more to say about the clone method in Chapter 6.

java.lang.Class 1.0

  • String getName()

    returns the name of this class.

  • Class getSuperclass()

    returns the superclass of this class as a Class object.


       

    Категории