Sub topic 8
Recognize Object as the Root Superclass
What you will learn
In earlier chapters you wrote class Dog extends Animal. You saw that Dog inherits from Animal. This chapter goes one level higher. Every Java class has a parent at the very top, and that parent is a class named Object.
This chapter assumes you know how to write classes, fields, methods, and constructors, and how to compile and run a Java program. You will learn:
- What
Objectis and why every class inherits from it. - Which methods you get for free:
toString(),equals(),hashCode(), andgetClass(). - How to override
toString()andequals()so your objects behave in useful ways. - Why a variable of type
Objectcan hold any object.
What is Object?
Object is a class in the java.lang package. A package is a named group of related classes. Java imports java.lang automatically, so you can write Object without an import line.
Object is the root superclass. A superclass is a class that another class extends. "Root" means Object has no superclass of its own. It sits at the top of every inheritance chain.
Every class extends Object
Look at this class:
class Cat {
}You did not write extends, but Java treats it as if you had written this:
class Cat extends Object {
}If a class has no extends clause, the compiler makes Object its superclass. This is automatic.
What if a class does extend something? Take Dog extends Animal, where Animal has no extends clause. Animal extends Object, so Dog reaches Object through Animal. Every class is a direct or indirect subclass of Object.
Because of this, every object you create has the methods that Object defines. This holds even when you write nothing yourself.
The methods every object has
Object defines several methods. These four matter most to a beginner.
| Method | What it does by default |
|---|---|
| `toString()` | Returns a text description made of the class name, an `@` sign, and a number in hexadecimal. |
| `equals(Object other)` | Returns `true` only if `other` is the very same object in memory. |
| `hashCode()` | Returns an `int` code for the object. The default is based on the object's identity. |
| `getClass()` | Returns an object that describes the real class of this object. |
Hexadecimal is a way of writing numbers using the digits 0 to 9 and the letters a to f.
Seeing the defaults
Here is a class that overrides nothing. We call the inherited methods anyway.
class Cat {
}
public class Main {
public static void main(String[] args) {
Cat a = new Cat();
Cat b = new Cat();
Cat c = a;
System.out.println(a.getClass().getName());
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a == c);
System.out.println(a.toString().startsWith("Cat@"));
}
}This prints:
Cat
false
true
true
trueHere is what each line shows:
getClass().getName()gives the class name,Cat.a.equals(b)isfalse. The two cats are separate objects, so the defaultequalssays they are different.a.equals(c)istrue, becausecpoints to the same object asa.a == cis alsotrue. For objects,==compares references, meaning it checks whether two variables point to the same object. The defaultequalsbehaves the same way.- The text from
toString()starts withCat@. The number after the@changes from run to run, so the example only tests the beginning.
Printing the default toString() result is rarely useful. You will see output like Cat@1b6d3586. Nothing in it tells you about the cat.
Overriding toString
Overriding means writing a method in a subclass with the same name and parameters as one in the superclass. The subclass version replaces the inherited one. You learned this earlier for Animal and Dog. Here the superclass is Object.
class Cat {
private final String name;
private final int age;
Cat(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Cat[name=" + name + ", age=" + age + "]";
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat("Tom", 3);
System.out.println(cat);
System.out.println("My pet is " + cat);
}
}This prints:
Cat[name=Tom, age=3]
My pet is Cat[name=Tom, age=3]Notice that we never wrote cat.toString(). System.out.println and the + operator on strings both call toString() for you. This is polymorphism at work. The calling code only knows it has an Object, and Java runs the toString() of the real class.
toString() is declared public in Object. An override cannot be less visible than the method it overrides. That is why the override above says public. If you left it out, the code would not compile.
Overriding equals and hashCode
Sometimes two separate objects should count as equal. Two Cat objects with the same name and age may be "the same cat" for your program. To get that, override equals.
The parameter of equals must be of type Object. It has to match the method in Object exactly, or you are not overriding it.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class Cat {
private final String name;
private final int age;
Cat(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Cat that = (Cat) other;
return age == that.age && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
public class Main {
public static void main(String[] args) {
Cat a = new Cat("Tom", 3);
Cat b = new Cat("Tom", 3);
Cat c = new Cat("Kit", 1);
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.equals(null));
Set<Cat> cats = new HashSet<>();
cats.add(a);
cats.add(b);
System.out.println(cats.size());
}
}This prints:
true
false
false
1The steps inside equals follow a common pattern:
- If both references point to the same object, return
true. - If
otherisnull, or its real class is different, returnfalse. - Cast
othertoCat. A cast tells the compiler to treat the value as a more specific type. It is safe here because step 2 already checked the class. - Compare the fields.
Objects.equalshandles the case where a field isnull.
The last lines show why hashCode matters. A HashSet is a collection that holds no duplicates. It uses hashCode() to find where to store each object. Because a and b are equal and have the same hash code, the set keeps only one of them.
Object as a type
Since every class is a subclass of Object, a variable of type Object can refer to any object. This is subtype polymorphism again, with Object as the widest supertype.
public class Main {
public static void main(String[] args) {
Object thing = "hello";
System.out.println(thing);
thing = 42;
System.out.println(thing);
thing = new int[] {1, 2, 3};
System.out.println(thing instanceof int[]);
}
}This prints:
hello
42
trueA String, a number (wrapped automatically as an Integer), and an array all fit in an Object variable. Arrays are objects too, so they are also subclasses of Object.
There is a cost. Through an Object variable you can only call methods that Object has. This line does not compile:
Object thing = "hello";
int n = thing.length(); // error: Object has no length() methodTo use length(), you cast back: ((String) thing).length(). If the object is not a String, the cast fails at run time with a ClassCastException. Check first with instanceof, as in the array example above.
Object and constructors
Constructor chaining, from the earlier chapter, ends at Object. Every constructor starts with a call to a superclass constructor. If you do not write super(...), Java inserts super() for you. In a class that extends nothing, that call goes to the no-argument constructor of Object, which does nothing visible. So the chain always ends there, even when you cannot see it.
Interfaces and Object
An interface is not a class and has no superclass. Still, a variable of an interface type can call toString(), equals(), and hashCode(). Java guarantees that every object behind such a variable is a subclass of Object. Interfaces are covered in a later chapter.
Common mistakes
- Writing
equals(Cat other)instead ofequals(Object other). This is overloading, not overriding. It makes a second method, and collections will still call the originalequals(Object).@Overridecatches this mistake. - Overriding
equalsbut nothashCode. See the warning above. - Comparing strings or objects with
==. Useequalswhen you want to compare contents. - Forgetting
publicontoString. The compiler rejects an override with weaker access.
Exercise
A class Bird has no extends clause and no methods. Does new Bird().toString() compile? Explain why, and say what kind of text it returns.
Show answer
Yes, it compiles. The compiler makes Object the superclass of Bird, so Bird inherits toString(). It returns the class name, an @ sign, and a hexadecimal number, such as Bird@1b6d3586.
Exercise
You write public boolean equals(Bird other) in class Bird and add @Override. What happens, and why?
Show answer
The code does not compile. Object declares equals(Object other), and equals(Bird other) has a different parameter type, so it overloads the method instead of overriding it. @Override makes the compiler report this error. The fix is to change the parameter type to Object and cast inside the method.
Exercise
Two Bird objects are equal according to your equals method but return different hash codes. What problem can this cause?
Show answer
A HashSet or HashMap can treat them as different objects and store both, or it can fail to find an object you added earlier. Equal objects must return the same hash code, so you must override hashCode whenever you override equals.