Sub topic 8
Recognize Object as the Root Superclass
What Object Is
A class is a blueprint for making objects. A superclass is the class that another class extends, which means it is the parent class. The subclass is the child that inherits from it.
Java has one special class called Object. It sits at the top of every inheritance chain. Every class in Java is a subclass of Object, either directly or through another class. You do not have to write extends Object. Java adds it for you.
> Every class you write already extends Object, even when you don't say so.
Seeing It Work
Here is a simple class with no extends keyword:
class Book {
String title;
Book(String title) {
this.title = title;
}
}
public class Main {
public static void main(String[] args) {
Book book = new Book("Dune");
System.out.println(book.getClass().getName());
System.out.println(book.toString());
}
}The first line prints Book. The second line prints something like Book@1b6d3586. The number after the @ can be different on your computer. It comes from Object's default toString() method, which every object inherits.
Methods You Get from Object
Because every class extends Object, every object has these methods:
| Method | What it does by default |
|---|---|
| `toString()` | Returns a text description, such as `Book@1b6d3586` |
| `equals(Object)` | Returns `true` only if both variables point to the same object |
| `hashCode()` | Returns a number used by hash-based collections |
| `getClass()` | Returns the class the object was made from |
You can replace some of these methods with your own versions. This is called overriding. For example, you can make toString() return something more useful:
class Book {
String title;
Book(String title) {
this.title = title;
}
@Override
public String toString() {
return "Book: " + title;
}
}
public class Main {
public static void main(String[] args) {
Book book = new Book("Dune");
System.out.println(book);
}
}This prints Book: Dune. The @Override tag is an annotation, which is a note for the compiler. It tells Java that you mean to replace a method from a superclass. If you make a mistake in the method name or type, the compiler will warn you.
Why It Matters
Because every object is an Object, you can store any object in an Object variable:
Object item = new Book("Dune");
System.out.println(item.toString());This is useful when you need one variable to hold many kinds of objects. It also means that every object can be printed, compared, and identified in the same way.
Exercise
What is the superclass of the class class Car { } if you write nothing after its name?
Show answer
Object. Java adds extends Object for you, so Car is a direct subclass of Object.
Exercise
If a class does not override toString(), what does System.out.println(car) print?
Show answer
It prints the class name, an @ sign, and a hexadecimal number, such as Car@7a81197d. This comes from the default method in Object.