Memra

Object: the root of every class

◈ 4 cards

Every class extends Object — what toString, equals, and hashCode do by default.

Every class secretly extends Object

If your class has no extends clause, Java implicitly inserts extends Object. Every object therefore inherits a set of methods from java.lang.Object. Three are critical:

toString() — called by println and string concatenation. The default produces a practically useless type-tag and hash:

Dog d = new Dog("Rex", 3);
System.out.println(d);   // Dog@6d06d69c

equals(Object other) — the default compares references (identity), exactly like ==. Two separate new Dog("Rex", 3) objects are not equal by default even though they hold the same data:

Dog a = new Dog("Rex", 3);
Dog b = new Dog("Rex", 3);
System.out.println(a.equals(b));  // false — different objects
System.out.println(a == b);       // false — different references

hashCode() — the default returns an integer derived from the object's memory address. The contract: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). Violating this contract breaks HashMap and HashSet.

In the next module you will learn to override all three — toString() for readable output, and equals/hashCode together to enable value-based equality in collections.

abDog("Rex", 3)one objectDog("Rex", 3)another objecta.equals(b) is false
Object.equals asks “is this the same object?”, not “is this the same data?”. Two arrows to two boxes make both a.equals(b) and a == b false until the class overrides equals.
NORMAL ~/memra/learn/java-from-zero/object-class-basics utf-8 LF