נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
15
חלק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.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • כימוס: העצם שומר על הנתונים שלו בעצמו: השדות private, ומבחוץ אפשר לשנות אותם רק דרך מתודות שבודקות שהשינוי חוקי.encapsulation: The object guards its own data: the fields are private, and from outside they change only through methods that check the change is valid.
  • private: שדה או מתודה שנגישים רק מתוך המחלקה עצמה. מבחוץ javac עוצר: rating has private access in Book.private: A field or method reachable only inside its own class. From outside javac stops: rating has private access in Book.
  • getter ו-setter: getRating() מחזירה ערך, ו-setRating(int) משנה אותו (עם בדיקה). לא לכל שדה צריך setter: רק למה שבאמת אמור להשתנות.getter and setter: getRating() returns a value, and setRating(int) changes it (with a check). Not every field needs a setter: only what really should change.
  • אינווריאנט: כלל שתמיד נכון על העצם, למשל "הדירוג בין 1 ל-5". הבנאי וה-setters זורקים חריגה במקום לשבור אותו.invariant: 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.
  • עצם בלתי משתנה: עצם שלא משתנה אחרי שנוצר: כל השדות private final, ו"שינוי" מחזיר עצם חדש (כמו String). בטוח לשתף אותו.immutable object: An object that never changes after it's made: every field private final, and a "change" returns a new object (like String). Safe to share.
  • העתקה מגינה: מחזירים עותק (או תצוגה לקריאה בלבד) של אוסף פנימי, כדי שאיש לא ישנה אותו מבחוץ: return List.copyOf(songs);.defensive copy: Return a copy (or a read-only view) of an inner collection, so nobody changes it from outside: return List.copyOf(songs);.

02setter ששומר על הכלליםA setter that guards the rules

rating הוא private, ולכן הדרך היחידה לשנות אותו היא setRating, שזורקת חריגה על ערך לא חוקי. הכלל "בין 1 ל-5" לא נשבר אף פעם. ל-title אין setter בכלל: הוא final.

rating is private, so the only way to change it is setRating, which throws on an illegal value. The rule "between 1 and 5" is never broken. title has no setter at all: it's final.

Main.java
public class Main {
    public static void main(String[] args) {
        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());
    }
}

class Book {
    private final String title;
    private int rating = 3;

    Book(String title) {
        this.title = title;
    }

    String getTitle() {
        return title;
    }

    int getRating() {
        return rating;
    }

    void setRating(int rating) {
        if (rating < 1 || rating > 5) {
            throw new IllegalArgumentException("Rating must be 1-5, got " + rating);
        }
        this.rating = rating;
    }
}
פלטOutput
Rating must be 1-5, got 42
Dune 4
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03מבחוץ אי אפשר לגעתYou can't touch it from outside

ניסיון לכתוב לשדה private ממחלקה אחרת נעצר כבר בקומפילציה.

Trying to write a private field from another class is stopped at compile time.

טעות נפוצהCommon mistake

מבחוץ אי אפשר לגעת

You can't touch it from outside

Main.java
public class Main {
    public static void main(String[] args) {
        Book b = new Book();
        b.rating = 42;
    }
}

class Book {
    private int rating = 3;
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:4: error: rating has private access in Book
        b.rating = 42;
         ^
1 error
בעברית פשוטה: In plain words: rating has private access in Book: רק הקוד בתוך Book רשאי לגעת ב-rating.rating has private access in Book: only the code inside Book may touch rating.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04עצם שלא משתנהAn object that never changes

בעצם בלתי משתנה "הזזה" יוצרת נקודה חדשה. בזיכרון רואים שתי נקודות: p נשארה (1, 2). final class אומר שאי אפשר לרשת ממנה ולשנות את ההתנהגות.

In an immutable object a "move" creates a new point. In memory you see two points: p stayed (1, 2). final class means nobody can extend it and change the behaviour.

Main.java
public class Main {
    public static void main(String[] args) {
        Point p = new Point(1, 2);
        Point q = p.moveBy(10, 0);
        System.out.println(p.x() + "," + p.y() + " -> " + q.x() + "," + q.y());
    }
}

final class Point {
    private final int x;
    private final int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    int x() {
        return x;
    }

    int y() {
        return y;
    }

    Point moveBy(int dx, int dy) {
        return new Point(x + dx, y + dy);
    }
}
פלטOutput
1,2 -> 11,2
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

ויזואלייזר זיכרוןMemory visualizerעצם שלא משתנהAn object that never changes

מה קורה עכשיוWhat happens now

פלטOutput

Stack: משתנים בכל מתודהStack: each method's variables

Heap: העצמיםHeap: the objects

05טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: מיליונר בקיצור דרך

Bug hunter: a shortcut millionaire

Main.java
public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.balance = 1000000;
        System.out.println(acc.getBalance());
    }
}

class Account {
    private int balance = 0;

    void deposit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must be positive");
        }
        balance += amount;
    }

    int getBalance() {
        return balance;
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:4: error: balance has private access in Account
        acc.balance = 1000000;
           ^
1 error
בעברית פשוטה: In plain words: balance has private access in Account: היתרה מוגנת, ומשנים אותה רק דרך deposit.balance has private access in Account: the balance is protected, and it changes only through deposit.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06הצעד של היום בפרויקט מדףToday's step in the Shelf project

ל-Book יש private final String title ו-private int rating = 3, getters, ו-setRating שזורקת Rating must be 1-5, got 7. קבעו 4, נסו 7 (הדפיסו את ההודעה), והדפיסו Dune 4.

Book has private final String title and private int rating = 3, getters, and setRating throwing Rating must be 1-5, got 7. Set 4, try 7 (print the message), and print Dune 4.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich