Memra

Object: the root of every class

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.

NORMAL ~/memra/learn/java-from-zero/object-class-basics utf-8 LF