Object class
- Java course
- Intermediate
- Lesson 16/116
- 5 min
Learn the Object class and equals/hashCode.
The Object class
In Java all classes implicitly inherit from the Object class. Even if a class does not specify extends, it is a subclass of Object. Object provides methods like toString, equals and hashCode.
Example: If you write class Book { }, Book automatically inherits from Object. Calling new Book().toString() works; by default it returns the class name and memory location. You can override toString, equals and hashCode to define your own behavior. These methods play an important role in collections and comparisons.
The equals method
The equals method determines whether two objects are equal. The default Object.equals compares references; it checks whether they are the same object. To compare by content, you override equals.
Example: In a Book class, two books are equal if their title matches. You write @Override public boolean equals(Object o) { ... } to compare the title field. When equals is overridden, hashCode must also be overridden; the two work together. Collections use these two methods to find and group objects.
Practice Override toString in the Book class
Define a class Book with String title and int pages fields. Add a @Override public String toString() method returning title + " (" + pages + " pages)". In main create a Book instance, assign values and print the instance with println.
Starter code
// Define the Book class
// Override the toString method
// Instantiate and print in mainSample solution
class Book {
String title;
int pages;
@Override
public String toString() {
return title + " (" + pages + " pages)";
}
public static void main(String[] args) {
Book b = new Book();
b.title = "Java";
b.pages = 320;
System.out.println(b);
}
}Expected output
Java (320 pages)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Override toString from Object
class Book {
String title;
@Override
public ____ toString() {
return title;
}
}
class Book {
String title;
@Override
public String toString() {
return title;
}
}
Explanation: toString must return a String.
2 Match the Object methods
| Term | Meaning |
|---|---|
toString |
String conversion |
equals |
Equality comparison |
hashCode |
Hash value |
Object |
Superclass of all |
3 Which class do all classes inherit from?
- String
- Object Correct answer
- System
- Class
Explanation: Object — all classes implicitly inherit from Object.