בנאים ו-thisConstructors & this
בנאים, overloading של בנאים, this() ו-this.field, וסדר האתחול.
Constructors, constructor overloading, this() and this.field, and initialization order.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- בנאי: "מתודה" מיוחדת בשם המחלקה, בלי טיפוס החזרה, שרצה ב-
new:Book(String title) { this.title = title; }.constructor: A special "method" named after the class, with no return type, that runs onnew:Book(String title) { this.title = title; }. - this: הפניה לעצם הנוכחי.
this.titleהוא השדה, ו-titleלבד הוא הפרמטר אם יש פרמטר בשם הזה.this: A reference to the current object.this.titleis the field, and plaintitleis the parameter if there's a parameter with that name. - הסתרה: כשלפרמטר או למשתנה מקומי יש שם של שדה, הוא "מסתיר" את השדה.
title = title;משים את הפרמטר לעצמו, והשדה נשארnull.shadowing: When a parameter or local variable has a field's name, it "hides" the field.title = title;assigns the parameter to itself, and the field staysnull. - שרשור בנאים:
this(...)בשורה הראשונה של בנאי קורא לבנאי אחר של אותה מחלקה. כך כותבים את האתחול פעם אחת, ובנאים קצרים מוסיפים ברירות מחדל.constructor chaining:this(...)on a constructor's first line calls another constructor of the same class. That way the setup is written once, and short constructors add defaults. - בנאי ברירת מחדל: אם לא כתבתם שום בנאי, Java נותנת בנאי ריק בלי פרמטרים. ברגע שכתבתם בנאי כלשהו, הוא נעלם.default constructor: If you wrote no constructor, Java gives an empty one with no parameters. As soon as you write any constructor, it's gone.
- סדר האתחול: ב-
new: כל השדות מקבלים 0,nullאוfalse, אחר כך רצים האתחולים שליד השדות (int a = 5;), ורק אז גוף הבנאי.initialization order: Onnew: every field gets 0,nullorfalse, then the initializers next to the fields run (int a = 5;), and only then the constructor body.
02בנאי: אתחול בשורה אחתA constructor: setup in one line
בנאי רץ ב-new ומקבל ערכים. this.title הוא השדה, title הוא הפרמטר. בזיכרון רואים את המסגרת new Book עם this שמצביע על העצם החדש.
A constructor runs on new and takes values. this.title is the field, title is the parameter. In memory you see the new Book frame with this pointing at the new object.
public class Main {
public static void main(String[] args) {
Book a = new Book("Dune", 1965);
Book b = new Book("Emma", 1815);
System.out.println(a.title + " " + a.year + ", " + b.title + " " + b.year);
}
}
class Book {
String title;
int year;
Book(String title, int year) {
this.title = title;
this.year = year;
}
}Dune 1965, Emma 1815
צפו בהרצה צעד אחר צעד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כמה בנאים ו-this(...)Several constructors and this(...)
בנאי קצר מעביר את העבודה לבנאי המלא עם this(title, "unknown"). כך האתחול כתוב במקום אחד.
A short constructor hands the work to the full one with this(title, "unknown"). That way the setup lives in one place.
public class Main {
public static void main(String[] args) {
Book a = new Book("Dune", "Herbert");
Book b = new Book("Notes");
System.out.println(a.title + " by " + a.author);
System.out.println(b.title + " by " + b.author);
}
}
class Book {
String title;
String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
Book(String title) {
this(title, "unknown");
}
}Dune by Herbert Notes by unknown
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04הבנאי הריק נעלםThe empty constructor disappears
ברגע שכתבתם Book(String title), Java כבר לא נותנת Book(). javac עוצר ומסביר מה נדרש ומה נמצא.
As soon as you write Book(String title), Java no longer gives you Book(). javac stops and explains what's required and what was found.
הבנאי הריק נעלם
The empty constructor disappears
public class Main {
public static void main(String[] args) {
Book b = new Book();
System.out.println(b.title);
}
}
class Book {
String title;
Book(String title) {
this.title = title;
}
}Main.java:3: error: constructor Book in class Book cannot be applied to given types;
Book b = new Book();
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 errorconstructor Book in class Book cannot be applied to given types;: יש רק בנאי שמקבל String, ו-new Book() לא נותן כלום.constructor Book in class Book cannot be applied to given types;: there's only a constructor taking a String, and new Book() gives nothing.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05סדר האתחולInitialization order
כשהבנאי מתחיל, a כבר 5 (האתחול שליד השדה רץ קודם), ו-b עדיין 0. רק אחר כך הבנאי קובע את b.
When the constructor starts, a is already 5 (the initializer next to the field ran first), and b is still 0. Only then does the constructor set b.
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println("after: a=" + d.a + " b=" + d.b);
}
}
class Demo {
int a = 5;
int b;
Demo() {
System.out.println("in constructor: a=" + a + " b=" + b);
b = a * 2;
}
}in constructor: a=5 b=0 after: a=5 b=10
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06טעויות נפוצות, ומה 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: no empty constructor
public class Main {
public static void main(String[] args) {
Book b = new Book();
System.out.println(b.title);
}
}
class Book {
String title;
Book(String title) {
this.title = title;
}
}Main.java:3: error: constructor Book in class Book cannot be applied to given types;
Book b = new Book();
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 errorconstructor Book in class Book cannot be applied to given types;: הבנאי היחיד דורש String. מוסיפים Book() { this("Untitled"); }.constructor Book in class Book cannot be applied to given types;: the only constructor needs a String. Add Book() { this("Untitled"); }.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
07הצעד של היום בפרויקט מדףToday's step in the Shelf project
ל-Book יש title, author, year, rating. בנאי מלא, ובנאי Book(String title, String author) שנותן שנה 0 ודירוג 3. line() מחזירה Dune by Herbert (1965) rating 5, ולשנה 0 unknown year. הדפיסו את Dune ואת new Book("Notes", "Me").
Book has title, author, year, rating. A full constructor, and Book(String title, String author) giving year 0 and rating 3. line() returns Dune by Herbert (1965) rating 5, and for year 0 unknown year. Print Dune and new Book("Notes", "Me").
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.