5.7 Object Superclass
From CS Awesome 2CC BY-NC-SA 4.0Original page
Java1 class period5 exercises6 graded tests
Files
5.7 Object Superclass
Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.
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? The AP CSA Java Quick Reference Sheet lists the two main methods that are most frequently used:
String toString()boolean equals(Object other)
toString() method
One commonly overridden 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.
In the following code, the Person class overrides the toString method from Object method and the Student class then overrides it again. In each class the new toString method adds the new attributes from that class.
Exercise 1
After trying the code, complete the 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. Uncomment the APStudent object in the main method to test it.
Open the
01-toStringDemofolder and editPerson.java. Press Run to try it; Run Tests checks it (2 tests).
equals Method
One of the important methods inherited from Object 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 you can see if you run the code below, the equals method inherited from Object only returns true if the two objects references refer to the same object. In other words it is does the same test as ==.
Exercise 2
Try to guess what this code will print out before running it.
Open the
02-ObjEqualsfolder and runPerson.java. It is an example, so it has no tests.

A picture from the Java Visualizer showing that only p3 and p4 refer to the same object.
Overriding the equals Method
The equals method defined in Object and thus inherited by all classes only considers two object references equivalent if they refer to exactly the same object. But we saw in Unit 2 that the String class provides an equals method that considers two String objects equivalent if they have the same characters in the same order, even if they are actually different objects. How does that work?
It is because the String class has overridden the equals method it inherited from Object to provide a definition of equality that makes more sense.
As we saw in previous lessons, a class can override inherited methods by providing a method with the same method signature (method name, parameter types, and return type). String has done that with equals so when we compare String objects with equals that new method will be called instead of the inherited one.
Exercise 3
Try to guess what this code will print out before running it.
Open the
03-StringTest1folder and runStringTest.java. It is an example, so it has no tests.
However, overriding equals is a bit more involved than overriding toString. While the toString method is only required to produce a reasonable human-readable String representation of an object, equals has to meet a more complex set of requirements in order to be useful.
You will not be expected to write your own equals method on the AP exam but it’s worth looking at what those requirements are and how to satisify them. There are five requirements described in the Javadocs for equals in Object that a properly implemented equals must satisfy:
- Equality is reflexive, meaning an object will be
equalsto itself:o.equals(o)istrue. - Equality is symmetric:
o1.equals(o2)returns the same value aso2.equals(o1). - Equality is transitive: if
o1.equals(o2)ando2.equals(o3)theno1.equals(o3). - Equality is consistent:
o1.equals(o2)always returns the same value assuming the objects are not modified. - No object is equal to
null:o.equals(null)is alwaysfalse.
The other way to look at these requirements is as guarantees that are made to you as a user of equals. If you look at it that way, these requirements are quite nice. Imagine how much harder it would be to use the String equals method if you couldn’t rely on the fact that s1.equals(s2) is necessarily the same as s2.equals(s1)!
So even though the Java compiler can’t force you to implement equals correctly, if you ever do want to override it, it’s important that you do. Let’s look at what’s involved.
We’ll write a class Word which represents a word in a particular language. We want two Word objects to be considered equals if and only if they are spelled the same and come from the same language. The latter requirement is because sometimes different languages have words that are spelled the same but with different meanings such as “pie” which in English is a tasty baked treat and in Spanish is what we call a “foot” in English.
Exercise 4
Try to guess what this code will print out before running it.
Open the
04-OverrideEqualsfolder and runWord.java. It is an example, so it has no tests.
The basic recipe for writing your own equals method, is:
- Use the
public boolean equals(Object other)method signature. Make sure the parameter type isObject, not the class you are defining. - Check of
this == otherto quickly returntruewhen comparing an object to itself. - Use
instanceofto check ifotheris an instance of this class and returnfalseif not. - Cast
otherto the current class. - Finally compare this object’s attributes to the other object’s with
==for primitive types likeintanddoubleandequalsfor reference types. If you need to compare multiple attributes&&together the comparisons of the individual attributes since two objects should only be equal if all the attributes match.
Note that the requirements on equals make it almost impossible to correctly override it in a subclass of a class that has already overridden the Object version. To see why, imagine if we made a subclass of Word, ClassifiedWord and added another attribute, partOfSpeech.
If we override equals in the ClassifiedWord to only consider two ClassifiedWord objects equals if their spelling, language, and part of speech match, that will break the symmetry since regularWord.equals(classifiedWord) will invoke the equals from Word which will only compare the spelling and language of the word but classifiedWord.equals(regularWord) will return false assuming the equals in ClassifiedWord checks that other is an instanceof ClassifiedWord. In general you should only provide an overridden equals method in one class in a class hierarchy.
Coding Challenge: Savings Account
The following code contains the beginning of a class for representing a bank account containing 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:
- Implement a
toStringmethod inAccountthat returns aStringrepresenting the instance variables inAccountin the form name, comma, space, balance. - Write a subclass called
SavingsAccountthat extendsAccountand adds an interest rate variable. - Write a constructor with 3 arguments (name, balance, interest rate) for the
SavingsAccountclass that uses the super constructor. - Write a
toStringmethod forSavingsAccountthat returns a string consisting of the result of the superclass’stoStringplus a comma, a space, and the interest rate.
Exercise 5
Complete the subclass SavingsAccount below which inherits from Account and adds an interest rate variable. Write a constructor with 3 arguments, a toString, and an equals method for it. Uncomment the code in main to test your new class and methods.
Open the
05-challenge-9-7-savingsaccountfolder and editAccount.java. Press Run to try it; Run Tests checks it (4 tests).
Summary
- The
Objectclass is the superclass of all other classes in Java and a part of the built-injava.langpackage. - The following
Objectclass methods are part of the Java Quick Reference:String toString()boolean equals(Object other)
- Subclasses of Object often override the
toStringandequalsmethods with class-specific implementations. - When overriding
equals, it’s important to satisfy all the requirements of a correct implementation.
For teachers
5.7 Object Superclass
Students read CSAwesome2's “Object Superclass” in CS Room and work through its 5 Java coding exercises (2 graded, 3 examples).
- Time: 1 class period
- Tests: 6 in 2 graded exercises, set up for you when you import the lesson
Goals
- The
Objectclass is the superclass of all other classes in Java and a part of the built-injava.langpackage. - The following
Objectclass methods are part of the Java Quick Reference:String toString()boolean equals(Object other)
- Subclasses of Object often override the
toStringandequalsmethods with class-specific implementations. - When overriding
equals, it’s important to satisfy all the requirements of a correct implementation.
Before class
- Import the lesson into your class from the Lessons page, or with New assignment → Use a lesson. It arrives as a draft with its tests already set up.
- Publish it.
- The original page is on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-7-Object.html
- CS Awesome's own teacher materials: the CS Awesome teacher site
In class
- Students read
README.md. - Students do exercises 01–05, each in its own folder, pressing Run to try their code.
- Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.
Exercises
| Folder | File | Grading | Tests |
|---|---|---|---|
01-toStringDemo | Person.java | Autograded | 2 |
02-ObjEquals | Person.java | Example, not graded | 0 |
03-StringTest1 | StringTest.java | Example, not graded | 0 |
04-OverrideEquals | Word.java | Example, not graded | 0 |
05-challenge-9-7-savingsaccount | Account.java | Autograded | 4 |
Teachers can download a reference solution after signing in.