Java
Object class
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.
Exercise 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.
Show example 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);
}
}
Test yourself
-
Override toString from Object
class Book {
String title;
@Override
public ____ toString() {
return title;
}
}
Show answer
class Book {
String title;
@Override
public String toString() {
return title;
}
}
-
Match the Object methods
- toString
- String conversion
- equals
- Equality comparison
- hashCode
- Hash value
- Object
- Superclass of all
-
Which class do all classes inherit from?
Show answer
Object — Object — all classes implicitly inherit from Object.
Next lesson: final class and method