Object Class Methods in Java
Problem
Every Java class implicitly extends Object, which means every object automatically comes with a default toString(), equals(), hashCode(), and getClass() — even a class that defines nothing of its own.
Create a plain Car class with no overrides, and observe the default behavior it inherits from Object.
Java Program
public class Car {
private String make;
public Car(String make) {
this.make = make;
}
public static void main(String[] args) {
Car car1 = new Car("Toyota");
Car car2 = new Car("Toyota");
System.out.println("Class name: " + car1.getClass().getName());
System.out.println("Default toString starts with class name: " + car1.toString().startsWith("Car@")); // avoids relying on the exact, non-deterministic hash
System.out.println("Default equals (different objects, same fields): " + car1.equals(car2));
}
}Output
Core Logic
Calling getClass(), toString(), and equals() on a class that overrides none of them reveals exactly what Object itself provides for free — a class name lookup, an identity-based string, and a reference-based comparison.
- 1
car.getClass().getName()returns"Car", the runtime class name — this works on any object at all, sincegetClass()comes from Object and can't be overridden. - 2
car.toString(), left unoverridden, returns a string in the formatClassName@hexHashcode— checking that itstartsWith("Car@")confirms the format without depending on the exact, non-deterministic hash value. - 3
car1.equals(car2)compares two separately-constructed Car objects with identicalmakevalues — since neither overridesequals(), this falls back to Object's reference comparison and reportsfalse, even though their fields match. - 4None of this required writing a single line of code in Car itself — every one of these methods came from Object automatically.
equals(), since it only compares whether the two references point to the same object.Key Point: This is the deliberate contrast with the dedicated toString(), equals(), and hashCode() override pages — those pages show what happens once you replace this default behavior; this page shows what you get before you do anything at all.