This book is now obsolete Please use CSAwesome instead.

11.7. The Equals Method

If a parent class isn’t specified using the extends keyword, the class will inherit from the Object class. What does a class inherit from the Object class? One of the important things that gets inherited is the equals(Object obj) method. This method is used to test if the current object and the passed object called obj are equal. But what does that mean?

11.7.1. The Inherited Equals Method from Object

The equals method that is inherited from the Object class only returns true if the two objects references refer to the same object.

The equals method inherited from the Object class only returns true when the two references point to the same object as shown in the code above and figure 1 below.

../_images/equalsEx.png

Figure 1: A picture from the Java Visualizer showing that only p3 and p4 refer to the same object.

11.7.2. String Overrides Equals

If you want to change how the inherited equals method works you can override it so that the new method is called instead of the inherited one. The String class overrides the inherited equals method to return true when the two objects have the same characters in the same order as shown in the code below.

11.7.3. Overriding the Inherited Equals Method

A class can override the inherited equals method by providing a method with the same method signature (method name and parameter list) and return type. The provided method will be called instead of the inherited one, which is why we say that the new method overrides the inherited method. The Person class below overrides the inherited equals method.

../_images/overrideEquals.png

Figure 2: A picture from the Java Visualizer showing the object references and objects.

You can step through this code in the Java Visualizer by clicking on the following link: OverrideEquals Ex.

You have attempted of activities on this page