Encapsulation: private fields, getters, setters · אקפסולציה: שדים פרטיים, מקבלים ומעמידים (getters, setters)
Protect your data
- Encapsulation means hiding an object's data and only changing it through methods.
- This keeps the data safe. Other code cannot put a bad value into it.
- The main tools are the words
privateandpublic.
הגן על הנתונים שלך
- Encapsulation (אקספולציה) פירונו הסתרת נתוני האובייקט ושינוים רק דרך מתודות.
- זה שמר על הבטיחות של הנתונים. קוד אחר לא יכול להכניס ערכים רעים לתוכו.
- הכלים העיקריים הם המילים
privateוpublic.
private fields
- Mark instance variables
privateso code outside the class cannot touch them directly. - Methods inside the same class can still use them.
- This is the normal style for AP CSA: fields are
private.
שדות private
- סימן משתני מופע כ
privateכך שקוד מחוץ למחלקה לא יוכל לגעת בהם ישירות. - מתודות בתוך אותו מחלקה עדיין יכולות להשתמש בהן.
- זהו הסגנון הרגיל עבור AP CSA: שדות הם
private.
public class BankAccount {
private double balance; // hidden from outside code
public BankAccount(double start) {
this.balance = start;
}
}
Accessors (getters)
- A field is private, so we add a
publicmethod to read it. - A method that returns a field is called an accessor or getter.
- It usually starts with
get, likegetBalance().
Accessors (getters)
- שדה הוא פרטי, לכן אנו מוסיפים מתודת
publicכדי לקרוא אותו. - מתודה שהחזירה שדה נקראת accessor או getter.
- היא בדרך כלל מתחילה ב
get, כמוgetBalance().
public class BankAccount {
private double balance;
public BankAccount(double start) {
this.balance = start;
}
public double getBalance() {
return this.balance;
}
}
Mutators (setters)
- A method that changes a field is called a mutator or setter.
- It can check the new value first and refuse a bad one.
- Below,
depositignores a negative amount, so the balance stays safe.
Mutators (setters)
- מתודה שמשנה שדה נקראת mutator או setter.
- הוא יכול לבדוק תחילה את הערך החדש לסרב על ערך שגוי.
- למטה,
depositמתעלם מסכום שלילי, ולכן המאזן נשאר בטוח.
public class BankAccount {
private double balance;
public BankAccount(double start) {
this.balance = start;
}
public void deposit(double amount) {
if (amount > 0) {
this.balance = this.balance + amount;
}
}
public double getBalance() {
return this.balance;
}
}
static vs instance
- An instance field belongs to one object. Each object has its own.
- A
staticfield belongs to the class itself — it is shared by all objects. - Below,
countrises by 1 every time anyRobotis built.
static מול instance
- שדה instance שייך לאובייקט אחד. לכל אובייקט יש משלו.
- שדה
staticשייך ל-class עצמו — הוא משותף לכל האובייקטים. - למטה,
countעולה ב-1 בכל פעם שכלRobotנוצר.
public class Robot {
private static int count = 0; // shared by all robots
public Robot() {
count = count + 1;
}
public static int getCount() {
return count;
}
}
toString()
toString()returns text that describes the object.- Java calls it automatically when you print the object or join it with
+. - It takes no parameters and returns a
String.
toString()
toString()מחזיר טקסט המתאר את האובייקט.- Java קוראת לו אוטומטית כשאתה מדפיסה את האובייקט או מחברת אותו עם
+. - אינה מקבל פרמטרים וחוזרת
String.
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
}
Common mistakes
- Make fields
privateand reach them through getters and setters. - A setter can check a value before storing it.
טעויות נפוצות
- הגדר שדות כ-
privateוהגיע אליהם דרך getters ו-setters. - setter יכול לבדוק ערך לפני שאחסנו אותו.
Now you try
- Fill in each class so its private data is changed only through safe methods.
- A hidden Harness builds the object, calls the methods, and checks the results.
- Press Run to compile, then Check answer.
כעת תנסו בעצמכם
- מלא כל class כך שהנתונים הפרטיים שלו ישתנו רק דרך שיטות בטוחות.
- hidden Harness בונה את האובייקט, קורא לשיטות ובודק את התוצאות.
- לחץ על Run להתקפלה, ולאחר מכן לחץ על Check answer.
Complete BankAccount. Keep balance private. deposit(amount) adds the amount only if it is greater than 0. withdraw(amount) subtracts only if the amount is greater than 0 and not more than the balance (no overdraft). getBalance() returns the balance. · השלם BankAccount. שמור על balance פרטי. deposit(amount) מוסיף את הסכום רק אם הוא גדול מ0. withdraw(amount) מחסר רק אם הסכום גדול מ0 וגם אינו עולה על המאזן (ללא גרירה). getBalance() מחזיר את המאזן.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete Temperature. The constructor stores an int degrees in a private field. toString() returns the degrees followed by C — for 21 it returns 21C. · השלם Temperature. הבונה אוסף מעלה זוויות int degrees בשדה פרטי. toString() מחזיר את המעלות שאחרייהן C — עבור 21 הוא מחזיר 21C.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete Widget. A private static field count starts at 0. Every time a Widget is built, the constructor adds 1 to count. The static method getCount() returns how many widgets have been built. · השלם Widget. שדה פרטי static בשם count מתחיל בערך 0. בכל פעם שמיוצר object של Widget, הבונה מוסיף 1 ל-count. השיטה static (method) getCount() מחזירה כמה ויג'טים (widgets) נוצרו.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.