The object class equals() method considers two object references to be equal if they have the same.


Next: 1.6.4 Help Methods, Packages, Up: 1.6.3 Inheritance and the Previous: 1.6.3 Inheritance and the

1.6.3.1 Overriding equals

As an example of inheritance, consider the method
public boolean equals[Object o];
which is defined in the class Object, the superclass of all Java classes. Any Java class that is defined without a designated superclass is an immediate subclass of the Object class. In the class Object, equals is defined to mean Object identity. Two object references are identical if and only if they refer to exactly the same object [produced by a particular new operation].

For some classes, identity is the appropriate definition for equality, but for many others it is not. In the built-in class String, the equals method is redefined to compare the sequences of characters in strings, so that copies of the same string are considered equal. The redefinition of equals only affects the class String and any subclasses that it might have. This selective form of method redefinition is called method overriding.


Finger Exercise Load the sample program intList into the DrJava Definitions window. Override the definition of equals for both Empty and Cons to match the definition of the equal? function in Scheme on lists of integers. The Scheme equal? function compares two lists to determine if they contain the same sequence of elements. Try evaluating a substantial set of test cases in the Interaction window of DrJava.


Exercise Load the saved program file ObjectList into the DrJava Definitions window. Override the definition of equals for both Empty and Cons to match the definition of the equal? function in Scheme. The Scheme equal? function uses the equal? method to compare elements.


Next: 1.6.4 Help Methods, Packages, Up: 1.6.3 Inheritance and the Previous: 1.6.3 Inheritance and the Corky Cartwright
2000-01-07

The Object class is the superclass of all other classes in Java and a part of the built-in java.lang package. 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? There are two main methods that are most used, toString[] and equals[Object], from the Object class at the bottom, which are covered in more detail below.

  • String toString[]

  • boolean equals[Object other]

10.7.1. toString[] method¶

One commonly overriden Object method is toString[], which is often used to print out the attributes of an object. It is a good idea to write your own toString[] method in every class. In a subclass, toString[] can call the superclass toString[] method using super.toString[] and then add on its own attributes.

Coding Exercise

In the following code, the Person class overrides the Object toString[] method and the Student class overrides the Person toString[] method. They each add on their attributes.

After trying the code below, add another subclass called APStudent that extends Student with a new attribute called APscore and override the toString[] method to call the superclass method and then add on the APscore. Create an APStudent object in the main method to test it.

10.7.2. equals Method¶

One of the important things that gets inherited from the Object superclass 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?

As seen in the code below, the equals method that is inherited from the Object class only returns true if the two objects references refer to the same object.

Coding Exercise

Try to guess what this code will print out before running it.

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.

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

10.7.3. Overriding the equals Method¶

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.

Coding Exercise

Try to guess what this code will print out before running it.

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

Coding Exercise

Try to guess what this code will print out before running it.

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.

To write your own equals method, you must:

  1. Use the public boolean equals[Object other] method signature

  2. Type cast other to your Classname

  3. Return whether this object’s attribute[s] equals the other object’s attribute[s] with == for primitive types like int and double, or equals for reference types like String or another class.

public boolean equals[Object other]
{
   // Type cast other to your Classname
   Classname otherObj = [Classname] other;
   // Check if attributes are equal
   return [this.attribute == otherObj.attribute];
   // or this.attribute.equals[otherObj.attribute] if attribute a String
}

If you need to check multiple attributes, for example a name and an address for Person objects, you can use && to combine tests.

return [this.attribute1 == otherObj.attribute1] &&
       this.attribute2.equals[otherObj.attribute2]

If you are writing an equals method for a subclass, you can call the superclass equals using the super keyword to check the attributes in the superclass and then check the attributes in the subclass.

return super.equals[otherObj] &&
       [this.attribute == otherObj.attribute]

10.7.4.
Programming Challenge : Savings Account¶

In the following code, a bank account class contains the account holder’s name and the money balance in the account.

Work in pairs to write the following code and test each part before moving on to the next step:

  1. Write a toString[] method for Account that returns the name and balance with a comma in between.

  2. Write an equals method for Account that checks that the name and balance are equal.

  3. Write a subclass called SavingsAccount that extends Account and adds an interest rate variable.

  4. Write a toString[] method for SavingsAccount that returns a call to the super toString[] method and the interest rate.

  5. Write an equals method for SavingsAccount that calls the superclass equals method and checks that the interest rates are equal.

Complete the subclass SavingsAccount below which inherits from Account and adds an interest rate variable. Write a toSTring and an equals method for it.

10.7.5. Summary¶

  • The Object class is the superclass of all other classes in Java and a part of the built-in java.lang package.

  • The following Object class methods and constructors, including what they do and when they are used, are part of the Java Quick Reference:

    • String toString[]

    • boolean equals[Object other]

  • Subclasses of Object often override the equals and toString methods with class-specific implementations.

You have attempted of activities on this page

How will you compare abstract classes and interfaces?

Differences between abstract classes and interfaces. From an object-oriented programming perspective, the main difference between an interface and an abstract class is that an interface cannot have state, whereas the abstract class can have state with instance variables.

Can objects of abstract classes be instantiated?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.

What is the difference between abstract class and concrete class?

An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along with the new statement. A concrete class can be instantiated directly, using a new keyword. Example: Invalid direct instantiation of an abstract class.

Are Nonabstract classes from which objects can be instantiated?

Chapter 08 Key Terms Review.

Chủ Đề