חלקPart 3: OOP: היסודותOOP: the basics
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
Encapsulation, getters, setters ו-immutabilityEncapsulation, getters, setters & immutability
private ו-public, שמירה על מצב תקין, getters ו-setters במידה, ועצמים שלא משתנים.
private and public, keeping state valid, getters and setters in moderation, and objects that never change.
הנקודות החשובותKey points
- כימוס: העצם שומר על הנתונים שלו בעצמו:encapsulation: The object guards its own data:
- private: שדה או מתודה שנגישים רק מתוך המחלקה עצמה.private: A field or method reachable only inside its own class.
ratingהוא private, ולכן הדרך היחידה לשנות אותו היאsetRating, שזורקת חריגה על ערך לא חוקי.ratingis private, so the only way to change it issetRating, which throws on an illegal value.- הכלל "בין 1 ל-5" לא נשבר אף פעם.The rule "between 1 and 5" is never broken.
- ניסיון לכתוב לשדה private ממחלקה אחרת נעצר כבר בקומפילציה.Trying to write a private field from another class is stopped at compile time.
- בעצם בלתי משתנה "הזזה" יוצרת נקודה חדשה.In an immutable object a "move" creates a new point.
- בזיכרון רואים שתי נקודות:
pנשארה (1, 2).In memory you see two points:pstayed (1, 2). balance has private access in Account:balance has private access in Account:- מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5
מונחיםTerms
- כימוסencapsulation: העצם שומר על הנתונים שלו בעצמו: השדות private, ומבחוץ אפשר לשנות אותם רק דרך מתודות שבודקות שהשינוי חוקי.The object guards its own data: the fields are private, and from outside they change only through methods that check the change is valid.
- privateprivate: שדה או מתודה שנגישים רק מתוך המחלקה עצמה. מבחוץ javac עוצר:
rating has private access in Book.A field or method reachable only inside its own class. From outside javac stops:rating has private access in Book. - getter ו-settergetter and setter:
getRating()מחזירה ערך, ו-setRating(int)משנה אותו (עם בדיקה). לא לכל שדה צריך setter: רק למה שבאמת אמור להשתנות.getRating()returns a value, andsetRating(int)changes it (with a check). Not every field needs a setter: only what really should change. - אינווריאנטinvariant: כלל שתמיד נכון על העצם, למשל "הדירוג בין 1 ל-5". הבנאי וה-setters זורקים חריגה במקום לשבור אותו.A rule that's always true about the object, e.g. "the rating is between 1 and 5". The constructor and setters throw instead of breaking it.
- עצם בלתי משתנהimmutable object: עצם שלא משתנה אחרי שנוצר: כל השדות
private final, ו"שינוי" מחזיר עצם חדש (כמוString). בטוח לשתף אותו.An object that never changes after it's made: every fieldprivate final, and a "change" returns a new object (likeString). Safe to share. - העתקה מגינהdefensive copy: מחזירים עותק (או תצוגה לקריאה בלבד) של אוסף פנימי, כדי שאיש לא ישנה אותו מבחוץ:
return List.copyOf(songs);.Return a copy (or a read-only view) of an inner collection, so nobody changes it from outside:return List.copyOf(songs);. - כימוסencapsulation: העצם שומר על הנתונים שלו בעצמו: השדות private, ומבחוץ אפשר לשנות אותם רק דרך מתודות שבודקות שהשינוי חוקי.The object guards its own data: the fields are private, and from outside they change only through methods that check the change is valid.
- privateprivate: שדה או מתודה שנגישים רק מתוך המחלקה עצמה. מבחוץ javac עוצר:
rating has private access in Book.A field or method reachable only inside its own class. From outside javac stops:rating has private access in Book. - getter ו-settergetter and setter:
getRating()מחזירה ערך, ו-setRating(int)משנה אותו (עם בדיקה). לא לכל שדה צריך setter: רק למה שבאמת אמור להשתנות.getRating()returns a value, andsetRating(int)changes it (with a check). Not every field needs a setter: only what really should change. - אינווריאנטinvariant: כלל שתמיד נכון על העצם, למשל "הדירוג בין 1 ל-5". הבנאי וה-setters זורקים חריגה במקום לשבור אותו.A rule that's always true about the object, e.g. "the rating is between 1 and 5". The constructor and setters throw instead of breaking it.
- עצם בלתי משתנהimmutable object: עצם שלא משתנה אחרי שנוצר: כל השדות
private final, ו"שינוי" מחזיר עצם חדש (כמוString). בטוח לשתף אותו.An object that never changes after it's made: every fieldprivate final, and a "change" returns a new object (likeString). Safe to share. - העתקה מגינהdefensive copy: מחזירים עותק (או תצוגה לקריאה בלבד) של אוסף פנימי, כדי שאיש לא ישנה אותו מבחוץ:
return List.copyOf(songs);.Return a copy (or a read-only view) of an inner collection, so nobody changes it from outside:return List.copyOf(songs);.
Cheatsheet
setter ששומר על הכלליםA setter that guards the rules
Book b = new Book("Dune");
b.setRating(4);
try {
b.setRating(42);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
System.out.println(b.getTitle() + " " + b.getRating());עצם שלא משתנהAn object that never changes
Point p = new Point(1, 2);
Point q = p.moveBy(10, 0);
System.out.println(p.x() + "," + p.y() + " -> " + q.x() + "," + q.y());שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
rating has private access in Book | מבחוץ אי אפשר לגעתYou can't touch it from outside | rating has private access in Book: רק הקוד בתוך Book רשאי לגעת ב-rating.rating has private access in Book: only the code inside Book may touch rating. |
balance has private access in Account | צייד באגים: מיליונר בקיצור דרךBug hunter: a shortcut millionaire | balance has private access in Account: היתרה מוגנת, ומשנים אותה רק דרך deposit.balance has private access in Account: the balance is protected, and it changes only through deposit. |