نموذج الكائنات في Java
في هذه الصفحة 8 موضوعات
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
نظرة عامة
الموضوعات
- Object
- equals()
- hashCode()
- toString()
- الهوية مقابل المساواة
تعلّم أولًا
60 دقيقة قراءة · 3 ساعة تدريب (تقدير)
مخرجات التعلم
- 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.
الدروس
المختبر والتمارين
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. |
أظهر الحلول
- 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.
الاختبار
Outcomes: O1 Object · O2 identity vs equality · O3 equals/hashCode · O4 toString.
اختبار ذاتي لك: لا توجد درجات، ولا يُحفظ أو يُرسل أي شيء. اختر إجابة ثم تحقق منها، ويمكنك المحاولة مرة أخرى كما تشاء.
الجزء العملي
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.
أخطاء شائعة
Overriding equals without hashCode; using mutable fields in hashCode.
التقييم
Contract quiz plus implementation exercise.
الصلة بالمسار الوظيفي
Essential for collections (BEG-030), hashing (BEG-041), and JPA entities (JNR-028).