Home > Articles > Programming > Java

This chapter is from the book

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:

  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. 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;
  4. 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;
  5. Cast otherObject to a variable of your class type:
    ClassName other = (ClassName) otherObject
  6. 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. }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020