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

JavaJava
10
חלקPart 2: מתודות ומערכיםMethods & arrays כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

static מול instancestatic vs instance

מה שייך למחלקה ומה שייך לעצם, מתי static הגיוני, ולמה main הוא static.

What belongs to the class and what belongs to an object, when static makes sense, and why main is static.

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

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

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

  • חבר static: שדה או מתודה ששייכים למחלקה עצמה, בעותק אחד: Ticket.count, Math.max. לא צריך עצם כדי להשתמש בהם.static member: A field or method that belongs to the class itself, in one copy: Ticket.count, Math.max. No object is needed to use them.
  • חבר מופע: שדה או מתודה בלי static: לכל עצם יש עותק משלו של השדה (a.n ו-b.n נפרדים), וקוראים למתודה דרך עצם.instance member: A field or method without static: every object has its own copy of the field (a.n and b.n are separate), and you call the method through an object.
  • הקשר סטטי: קוד בתוך מתודה static (כמו main). אין שם this, ולכן אי אפשר לפנות ישירות לשדה או למתודה של עצם: non-static method greet() cannot be referenced from a static context.static context: Code inside a static method (like main). There's no this there, so you can't reach an object's field or method directly: non-static method greet() cannot be referenced from a static context.
  • קבוע: static final: ערך אחד למחלקה שאי אפשר לשנות. נהוג לכתוב באותיות גדולות: static final double VAT = 0.17;.constant: static final: one value per class that can't change. Usually written in capitals: static final double VAT = 0.17;.
  • מחלקת עזר: מחלקה שכל המתודות שלה static, כמו Math ו-Arrays: אוסף כלים, בלי מצב משלה.utility class: A class whose methods are all static, like Math and Arrays: a toolbox with no state of its own.

02לכל עצם עותק משלוEvery object has its own copy

שדה בלי static הוא שדה של העצם: ל-a ול-b יש n נפרד. בזיכרון רואים שני עצמי Counter שונים ב-heap.

A field without static is an object's field: a and b each have their own n. In memory you see two separate Counter objects on the heap.

Main.java
public class Main {
    public static void main(String[] args) {
        Counter a = new Counter();
        Counter b = new Counter();
        a.click();
        a.click();
        b.click();
        System.out.println(a.n + " " + b.n);
    }
}

class Counter {
    int n = 0;

    void click() {
        n++;
    }
}
פלטOutput
2 1
צפו בהרצה צעד אחר צעד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לכל עצם עותק משלוEvery object has its own copy

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

פלטOutput

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

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

03שדה static: עותק אחד לכולםA static field: one copy for everyone

static int count שייך למחלקה: יש רק אחד, וכל עצם חדש מעלה אותו. ב-stack הוא מופיע בתור static, מחוץ לכל עצם, ו-id הוא של כל כרטיס בנפרד.

static int count belongs to the class: there's only one, and each new object bumps it. In the stack it shows up as static, outside every object, while id belongs to each ticket.

Main.java
public class Main {
    public static void main(String[] args) {
        Ticket a = new Ticket("Noa");
        Ticket b = new Ticket("Avi");
        System.out.println(a.id + " " + b.id + " " + Ticket.count);
    }
}

class Ticket {
    static int count = 0;
    String owner;
    int id;

    Ticket(String owner) {
        this.owner = owner;
        count++;
        id = count;
    }
}
פלטOutput
1 2 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שדה static: עותק אחד לכולםA static field: one copy for everyone

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

פלטOutput

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

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

04למה main הוא static, ומה קורה כששוכחיםWhy main is static, and what happens when you forget

ה-JVM קוראת ל-main בלי ליצור עצם, ולכן הוא static. מתוך הקשר סטטי אי אפשר לקרוא למתודה של עצם. javac עוצר עוד לפני הריצה. התיקון: להוסיף static למתודה, או לקרוא דרך עצם: new Main().greet().

The JVM calls main without creating an object, so it's static. From a static context you can't call an object's method. javac stops before anything runs. The fix: add static to the method, or call it through an object: new Main().greet().

טעות נפוצהCommon mistake

למה main הוא static, ומה קורה כששוכחים

Why main is static, and what happens when you forget

Main.java
public class Main {
    void greet() {
        System.out.println("Hi");
    }

    public static void main(String[] args) {
        greet();
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:7: error: non-static method greet() cannot be referenced from a static context
        greet();
        ^
1 error
בעברית פשוטה: In plain words: non-static method greet() cannot be referenced from a static context: greet שייכת לעצם, ו-main רץ בלי עצם.non-static method greet() cannot be referenced from a static context: greet belongs to an object, and main runs without one.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

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

צייד באגים: from a static context

Bug hunter: from a static context

Main.java
public class Main {
    int square(int x) {
        return x * x;
    }

    public static void main(String[] args) {
        System.out.println(square(5));
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:7: error: non-static method square(int) cannot be referenced from a static context
        System.out.println(square(5));
                           ^
1 error
בעברית פשוטה: In plain words: non-static method square(int) cannot be referenced from a static context: square היא מתודת מופע, ו-main סטטי. מוסיפים static ל-square (היא לא צריכה שום שדה של עצם).non-static method square(int) cannot be referenced from a static context: square is an instance method and main is static. Add static to square (it uses no field of any object).
צפו איפה זה נשבר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

כתבו מחלקת עזר ShelfUtil עם static String stars(int rating) (למשל 4 → ****-) ו-static double average(int[] ratings). עבור Dune 5, Emma 4, Ulysses 2 הדפיסו שורה לכל ספר (Dune *****) ובסוף Average: 3.67.

Write a utility class ShelfUtil with static String stars(int rating) (e.g. 4 → ****-) and static double average(int[] ratings). For Dune 5, Emma 4, Ulysses 2 print a line per book (Dune *****) and then Average: 3.67.

טיפ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