Java object model
On this page 8 topics
Overview
Topics
- Object
- equals()
- hashCode()
- toString()
- identity vs equality
Learn first
60 min of reading · 3 h of practice (estimate)
Learning outcomes
- Explain that every class extends
Objectand name its key methods. - Distinguish identity (
==) from equality (equals) and fix string comparison bugs. - Implement
equalsandhashCodeconsistently and explain the contract. - Override
toStringfor useful logging and debugging.
Lessons
Lab and exercises
Lab
BEG-026-LAB1 · Broken set
Outcomes: 2, 3, 4 · Time: ~1.5 h Put Money objects into a HashSet (treat it as a black box) with no overrides, with only equals, and with both equals and hashCode. Record the set size each time and explain the duplicates. Acceptance: correct implementation and explanation.
Exercises (assessment: contract quiz plus implementation exercise)
| ID | Outcome | Task |
|---|---|---|
| BEG-026-EX01 | 1 | List five methods every object inherits from Object, and say which three are most often overridden. |
| BEG-026-EX02 | 2 | Predict == and equals for: two literals "a", new String("a") vs a literal, two new Account(...) with the same data and no overrides. |
| BEG-026-EX03 | 2 | Fix: if (command == "quit"). |
| BEG-026-EX04 | 3 | Implement equals and hashCode for Customer(id, name) where id identifies the customer. |
| BEG-026-EX05 | 3 | Explain why a mutable field in hashCode can make an object "disappear" from a HashSet. |
| BEG-026-EX06 | 4 | Write a toString for Account that shows number and balance but not secrets. |
Show solutions
- EX01
toString,equals,hashCode,getClass,wait/notify(orclone). Most overridden:toString,equals,hashCode. - EX02
"a" == "a"true (shared literal),equalstrue;new String("a") == "a"false,equalstrue; two accounts:==false,equalsfalse. - EX03
"quit".equals(command)(also safe againstnull). - EX04 Compare
idonly:equalscheckso instanceof Customer c && id == c.id;hashCodereturnsLong.hashCode(id)orObjects.hash(id). - EX05 The object was stored under a bucket from its old hash; after the field changes, lookups use the new hash and look in another bucket.
- EX06
return "Account[" + number + ", balance=" + balance + "]"; - Outcome 3 is also covered by the lab and the quiz.
Quiz
Outcomes: O1 Object · O2 identity vs equality · O3 equals/hashCode · O4 toString.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
Contract quiz above plus implementation exercise BEG-026-EX04 and the broken-set lab. Pass: quiz 8/10 and a correct equals/hashCode pair with the duplicate behavior explained.
Common mistakes
Overriding equals without hashCode; using mutable fields in hashCode.
Assessment
Contract quiz plus implementation exercise.
Career relevance
Essential for collections (BEG-030), hashing (BEG-041), and JPA entities (JNR-028).