Lesson · The Object Class & Core Contracts
The Object methods: what every class inherits
15 min readObject Methods
toString, equals, hashCode, getClass, clone and the wait/notify family arrive in every class for free. Knowing each default and whether to keep, replace or avoid it is the entry ticket to the contracts chapter.
The garbled text that has no data in it
Printing an object that never defined toString surprises every beginner once:
Point p = new Point(2, 3); System.out.println(p); // Point@1b6d3586 ... what is this? class Point { @Override public String toString() { return "Point(2, 3)"; } }
Predict: where did Point@1b6d3586 come from? Nobody wrote it. Every class you create extends Object silently, and Object's default toString answers with the class name plus an identity hash, because Object cannot possibly know your fields. Override the method and the text becomes yours.
The inventory: what arrives for free
Everything below is inherited by every class ever written, and each entry has a default verdict:
| Method | Default behaviour | Verdict |
|---|---|---|
toString() | Class name plus an identity hash, like Point@1b6d3586 | Override for value types; five minutes well spent |
equals(Object) | Identity: this == other | Override when same data should mean equal; pair with hashCode |
hashCode() | An identity-based number | Override exactly when equals is overridden |
getClass() | The object's runtime class; final | Leave it |
clone() | A shallow field-by-field copy; needs Cloneable | Replace with a copy constructor |
wait(), notify(), notifyAll() | Thread coordination on the object's monitor | Know they exist; modern code uses the concurrency utilities |
finalize() | A deprecated cleanup hook | Avoid entirely |
Object is the root of every hierarchy, and it is real. The .getClass().getSimpleName() you have seen, the identity equals that surprised you, and the @1b6d3586 text all come from the same small class every type silently extends.
toString deserves five minutes
Three habits make the override do its job:
- Start with the class name:
Point(2, 3)beats2,3the day another class prints similar fields into the same log. - Show the value fields, hide the sensitive ones: logs, debuggers and string concatenation all call
toString; a password field must not ride along. - For humans, not parsers: if code needs to read the text back, that is a serialisation format with its own rules, not
toString.
The pair that must travel together is equals and hashCode. Overriding one without the other leaves maps and sets broken in ways the next two lessons take apart: for now, remember that toString is optional fashion and equals/hashCode is load-bearing structure.
The inherited toolbox · default, verdict, habit
pick a methodSignature as inherited
public String toString()
The default
Returns the class name plus an identity hash: Point@1b6d3586. Object cannot know your fields.
The habit
Override on value types: class name, key fields, no secrets. Logs, debuggers, concatenation and test failures all use it.
Why the lock methods live on Object
wait, notify and notifyAll are methods about locks, so why are they on the root class instead of a Lock class?
- Every object can be a monitor: the
synchronizedkeyword uses any object as its lock, and coordination methods had to live where every lock lives: on Object itself. - Modern Java rarely calls them directly:
java.util.concurrentand its higher-level tools replaced hand-rolled wait/notify for almost all code. - `finalize` is the cautionary tale of the same design: a method on every object, almost always wrong; it is deprecated, and
try-with-resourcesorCleaneris what clean-up code uses now.
Inherited does not mean intended for you. Some Object methods are for the runtime (getClass), some for your values (toString), and some for machinery you should reach through better tools.
The inherited-methods playbook
A new class, one pass over the free toolbox:
- Write toString for any type with data a human might read in a log: class name, key fields, no secrets.
- Decide what equality means: identity (the default, fine for services and entities) or value (override equals and hashCode together).
- Leave getClass alone; use it for logging and for the strict class check inside equals, never fight it.
- Skip clone; give the class a copy constructor or a static copy method instead.
- Never implement finalize; treat wait/notify as hidden machinery and use the concurrency utilities when the time comes.
Know the defaults, then decide once per class. Three quick decisions (toString, the equals/hashCode pair, clone) cover everything Object hands you; the rest is background you will recognize when it appears.
Every class silently extends Object, and the defaults are opinionated
toString prints class plus identity hash, equals and hashCode answer questions about identity, getClass is final truth about the runtime class, and clone, finalize plus the wait/notify family serve machinery. Override toString for readable values, override equals and hashCode as a pair when value equality is the meaning, and replace clone with a copy constructor.
Interview angles
What does every class inherit from Object?+
toString, equals, hashCode, getClass, clone, the wait/notify/notifyAll family and finalize, plus the implicit super() constructor chain that every class joins.
Each has a working default: identity answers for equals and hashCode, class-name-plus-hash for toString, final runtime truth for getClass. A class overrides some, ignores others and never implements finalize; knowing which is which is the point.
class Point { } // extends Object, silently new Point().getClass(); // class Point new Point().toString(); // Point@1b6d3586
Common misconception: That Object is an abstract idea. It is a real class whose defaults your code runs until you replace them.
Follow-up: Which of these methods does the runtime call on your behalf?
Why does the default toString look like `Point@1b6d3586`?+
It is the class name plus the identity-based hashCode in hexadecimal, which is all Object can know about your object. It has no idea your class has useful fields.
Overriding it fixes logs, debuggers, string concatenation and test failure messages in one stroke: "value: " + p calls toString too. Keep it human-oriented; parsers need a real serialisation format.
@Override public String toString() { return "Point(" + x + ", " + y + ")"; }
Common misconception: That the hex part is an address or a real hash of the fields. It is identity-derived; two equal-by-value objects print different text until equals and hashCode are overridden.
Follow-up: What changes about that hex text after overriding hashCode?
Why do wait, notify and notifyAll live on Object?+
Because any object can be a monitor: synchronized locks on whatever object you give it, so the coordination methods sit on the one type every lock has.
The design dates to the first Java threading model. Modern code coordinates through java.util.concurrent (queues, executors, latches) instead of hand-rolled wait/notify, but the methods remain for the raw monitor protocol.
synchronized (lock) { while (!ready) lock.wait(); // any object can wait/notify: it is the lock }
Common misconception: That the methods mean 'threads wait on objects' loosely. They wait on the object's monitor, with strict rules about holding the lock first.
Follow-up: What higher-level tool would replace this pattern today?
Why must equals and hashCode be overridden together?+
Hash-based collections locate objects by hashCode and then confirm with equals. Equal objects with different hashes land in different buckets, and the lookup never finds them.
The contracts chapter proves it with a failing HashMap lookup; here the rule suffices: if two objects can be equal, they must produce the same hash. Override one and forget the other and only collections notice, which is exactly how it ships to production.
// equal by value, but hashes differ: HashMap.get returns null map.put(new Point(2, 3), "here"); map.get(new Point(2, 3)); // null, until hashCode is fixed
Common misconception: That hashCode matters only for performance. It decides correctness of lookups; collisions cost speed, mismatched hashes cost results.
Follow-up: What is the cheapest correct way to compute a hashCode from fields?
What should replace clone and finalize?+
Copies should come from copy constructors or static copy factories; cleanup should come from try-with-resources, Cleaner, or plain explicit close methods. clone and finalize are design dead ends.
clone demands Cloneable, returns Object (forcing casts), performs shallow copies by default and cooperates badly with final fields and subclassing. finalize runs at an unknown time, maybe never, and was deprecated for removal.
Point copy = new Point(p); // copy constructor: clear, typed, deep if you make it so try (var in = new FileInputStream(file)) { ... } // cleanup you can see
Common misconception: That clone is the standard copy tool because Object ships it. The community verdict landed long ago: copy constructors and factories won.
Follow-up: What does a shallow clone share with the original?