מחלקות ועצמיםClasses & objects
מחלקה כתבנית ועצם כמופע, שדות ומתודות, new, והפניות בזיכרון (stack מול heap).
A class as a blueprint and an object as an instance, fields and methods, new, and references in memory (stack vs heap).
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- עצם: מופע של מחלקה:
new Book()יוצר עצם חדש ב-heap, עם עותק משלו של כל השדות.object: An instance of a class:new Book()creates a new object on the heap, with its own copy of every field. - שדה: משתנה שמוגדר בתוך מחלקה, מחוץ למתודות. כל עצם מחזיק ערך משלו:
a.title,b.title. שדה מספרי מתחיל ב-0, ושדה של עצם ב-null.field: A variable defined inside a class, outside the methods. Each object holds its own value:a.title,b.title. A number field starts at 0, an object field atnull. - new: יוצר עצם חדש ב-heap ומחזיר הפניה אליו:
Book b = new Book();.new: Creates a new object on the heap and returns a reference to it:Book b = new Book();. - heap: האזור בזיכרון שבו גרים העצמים. המשתנים ב-stack מחזיקים רק חצים (הפניות) אליהם.heap: The memory area where objects live. Variables on the stack hold only arrows (references) to them.
- null: הפניה שלא מצביעה על שום עצם. משתנה מסוג עצם שלא קיבל ערך, או תא חדש במערך של עצמים, הוא
null.null: A reference that points to no object. An object variable that got no value, or a new cell in an array of objects, isnull. - NullPointerException: החריגה כשמנסים לגשת לשדה או למתודה דרך
null. Java 21 אומרת בדיוק מה היה null:Cannot read field "title" because "b" is null.NullPointerException: The exception when you reach a field or method throughnull. Java 21 says exactly what was null:Cannot read field "title" because "b" is null.
02מחלקה היא תבנית, עצם הוא מופעA class is a blueprint, an object is an instance
class Book מתארת מה יש לכל ספר: שדות (title, pages) ומתודות (describe). כל new Book() יוצר עצם חדש עם שדות משלו. בתוך describe, title הוא השדה של העצם שעליו קראו למתודה.
class Book describes what every book has: fields (title, pages) and methods (describe). Every new Book() makes a new object with its own fields. Inside describe, title is the field of the object the method was called on.
public class Main {
public static void main(String[] args) {
Book a = new Book();
a.title = "Dune";
a.pages = 412;
Book b = new Book();
b.title = "Emma";
b.pages = 474;
a.describe();
b.describe();
}
}
class Book {
String title;
int pages;
void describe() {
System.out.println(title + ", " + pages + " pages");
}
}Dune, 412 pages Emma, 474 pages
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
פלטOutput
Stack: משתנים בכל מתודהStack: each method's variables
Heap: העצמיםHeap: the objects
03משתנה מחזיק הפניה, לא עצםA variable holds a reference, not an object
b = a מעתיק את החץ: שני המשתנים מצביעים על אותו ספר, ושינוי דרך b נראה דרך a. c = null הוא חץ שלא מצביע לשום מקום.
b = a copies the arrow: both variables point to the same book, and a change through b shows through a. c = null is an arrow pointing nowhere.
public class Main {
public static void main(String[] args) {
Book a = new Book();
a.title = "Dune";
Book b = a;
b.title = "Dune Messiah";
Book c = null;
System.out.println(a.title + " | " + (c == null));
}
}
class Book {
String title;
}Dune Messiah | true
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
פלטOutput
Stack: משתנים בכל מתודהStack: each method's variables
Heap: העצמיםHeap: the objects
04NullPointerExceptionNullPointerException
מערך חדש של עצמים מלא ב-null. כשהלולאה מגיעה לתא הריק, b.title מנסה לקרוא שדה של כלום. Java 21 אומרת בדיוק מה היה null.
A new array of objects is full of null. When the loop reaches the empty cell, b.title tries to read a field of nothing. Java 21 says exactly what was null.
NullPointerException
NullPointerException
public class Main {
public static void main(String[] args) {
Book[] shelf = new Book[2];
shelf[0] = new Book();
shelf[0].title = "Dune";
for (Book b : shelf) {
System.out.println(b.title);
}
}
}
class Book {
String title;
}Dune Exception in thread "main" java.lang.NullPointerException: Cannot read field "title" because "b" is null at Main.main(Main.java:7)
Cannot read field "title" because "b" is null בשורה 7: בסיבוב השני b הוא shelf[1], שאף אחד לא שם בו ספר.Cannot read field "title" because "b" is null on line 7: in the second round b is shelf[1], where nobody put a book.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיו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.
צייד באגים: מדף חצי ריק
Bug hunter: a half-empty shelf
public class Main {
public static void main(String[] args) {
Book[] shelf = new Book[2];
shelf[0] = new Book();
shelf[0].title = "Dune";
for (Book b : shelf) {
System.out.println(b.title);
}
}
}
class Book {
String title;
}Dune Exception in thread "main" java.lang.NullPointerException: Cannot read field "title" because "b" is null at Main.main(Main.java:7)
Cannot read field "title" because "b" is null: shelf[1] אף פעם לא קיבל ספר. בודקים b != null לפני שניגשים לשדה.Cannot read field "title" because "b" is null: shelf[1] never got a book. Check b != null before reaching the field.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06הצעד של היום בפרויקט מדףToday's step in the Shelf project
מחלקה Book עם title, author, year, ומתודות String line() (Emma by Austen (1815)) ו-boolean isClassic() (לפני 1950). שימו במערך את Emma (Austen, 1815), Dune (Herbert, 1965) ו-Ulysses (Joyce, 1922), הדפיסו שורה לכל ספר, ובסוף Classics: 2.
A class Book with title, author, year, and methods String line() (Emma by Austen (1815)) and boolean isClassic() (before 1950). Put Emma (Austen, 1815), Dune (Herbert, 1965) and Ulysses (Joyce, 1922) in an array, print a line per book, then Classics: 2.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.