9.7 Object Superclass
Classes can form a hierarchy where each of the subclasses has access to all of the public methods of a parent. At the top of the hierarchy is the Object class
, which is a part of the built-in java.lang
package. All other classes can use the Object
class through inheritance.
The Object
class contains several useful methods that are used and inherited by its subclasses. Two such methods are equals()
and toString()
.
The equals method compares two objects and is often overridden by a subclass. Using the Object
level version of the equals()
method, Java returns true only if the two objects are represented by the same object in memory. This is often not very helpful, as ==
also returns the same result, which is why this method is often overridden by subclasses.
One example where equals()
is overridden is the String
class. The String
class equals()
method compares each character of the string to determine if they are the same, not just if they are the same objects.
The toString()
method is another commonly used and commonly overridden method from the Object
class. When an object name is called with no method, the toString()
is returned as a String
representation of the object. The generic toString()
for an object is to return the object type followed by an @
symbol and then the unsigned hexadecimal representation of the object. This has limited value, which is why it is often overridden.
There are many examples where the toString()
method is overridden. For example, in the Person
class you’ve created earlier in this chapter, the toString()
method is overridden to return the name of the person:
-
Incorrect
Correct
No Answer was selected
Invalid Answer
Which of the following methods would you find in the
Object
class?
For this exercise, you are given 3 Object
class objects and 3 Ball
class objects. In theory, all three Objects
are the same and all 3 Ball
objects are the same, but based on the way they are created and the way that Java evaluates equality, not all three objects will be equal.
Your task is to start by printing out the 6 Object
and Ball
objects. Remember, the Object
class has a toString()
method and since a Ball
object extends the Object
class, we should see similarities between the Object
and Ball
class.
After printing them out, you should notice which objects are the same. Write two true
and two false
statements for each group, one using ==
and one using the equals()
method. Will these be the same?