מתודות, overloading ו-pass-by-valueMethods, overloading & pass-by-value
הגדרת מתודות, פרמטרים וערך החזרה, overloading, ומה באמת עובר למתודה: עותק של הערך, גם כשהערך הוא הפניה.
Defining methods, parameters and return values, overloading, and what really reaches a method: a copy of the value, even when the value is a reference.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- פרמטר: משתנה בהגדרת המתודה שמקבל ערך מבחוץ: ב-
int add(int a, int b),aו-bהם פרמטרים.parameter: A variable in the method's definition that receives a value from outside: inint add(int a, int b),aandbare parameters. - ארגומנט: הערך שנותנים לפרמטר בקריאה: ב-
add(2, 3)הארגומנטים הם 2 ו-3.argument: The value given to a parameter in a call: inadd(2, 3)the arguments are 2 and 3. - ערך החזרה: התשובה שמתודה מחזירה עם
return. הטיפוס שלה כתוב לפני שם המתודה.return value: The answer a method hands back withreturn. Its type is written before the method name. - void: מתודה
voidלא מחזירה ערך: היא עושה משהו (למשל מדפיסה) וחוזרת.void: Avoidmethod returns no value: it does something (like printing) and goes back. - מסגרת (frame): בכל קריאה למתודה נוצרת מסגרת חדשה ב-stack עם המשתנים שלה. כשהמתודה חוזרת, המסגרת נמחקת.stack frame: Every method call creates a new frame on the stack holding its variables. When the method returns, the frame is removed.
- העמסה (overloading): כמה מתודות עם אותו שם ופרמטרים שונים. Java בוחרת לפי הארגומנטים:
max(int, int)מולmax(double, double).overloading: Several methods with the same name and different parameters. Java picks by the arguments:max(int, int)vsmax(double, double). - העברה לפי ערך: ב-Java כל ארגומנט מועתק לפרמטר. למספר: המתודה לא יכולה לשנות את המשתנה של הקורא. להפניה: מועתקת ההפניה, ושתיהן מצביעות על אותו עצם.pass-by-value: In Java every argument is copied into the parameter. For a number: the method can't change the caller's variable. For a reference: the reference is copied, and both point to the same object.
- תחום (scope): האזור בקוד שבו משתנה קיים: משתנה שהוגדר בתוך מתודה או בלוק נעלם בסוף שלהם.scope: The part of the code where a variable exists: a variable declared in a method or block disappears at its end.
02מגדירים וקוראיםDefine and call
מתודה היא פעולה עם שם. בהגדרה: טיפוס ההחזרה, שם ופרמטרים. return מחזיר את התשובה. בסימולציה רואים את Java קופצת לתוך המתודה, ואת הקופסאות a ו-b שנוצרות שם.
A method is a named action. In the definition: the return type, a name and parameters. return hands back the answer. In the simulation you see Java jump into the method, and the boxes a and b created there.
public class Main {
static int add(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
int total = add(2, 3);
System.out.println(total);
System.out.println(add(10, total));
}
}5 15
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03void ומתודה שקוראת למתודהvoid, and a method calling a method
מתודה void לא מחזירה ערך. מתודות יכולות לקרוא זו לזו, וכל קריאה מקבלת מסגרת משלה.
A void method returns nothing. Methods can call each other, and each call gets its own frame.
public class Main {
static void line(int n) {
System.out.println("-".repeat(n) + " " + square(n));
}
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
line(3);
line(5);
}
}--- 9 ----- 25
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04Overloading: אותו שם, פרמטרים שוניםOverloading: same name, different parameters
Java בוחרת איזו גרסה להפעיל לפי הטיפוסים ומספר הארגומנטים.
Java picks which version to run from the types and the number of arguments.
public class Main {
static String describe(int n) {
return "int " + n;
}
static String describe(double d) {
return "double " + d;
}
static String describe(String s) {
return "String " + s;
}
static String describe(int a, int b) {
return "two ints " + (a + b);
}
public static void main(String[] args) {
System.out.println(describe(7));
System.out.println(describe(7.5));
System.out.println(describe("seven"));
System.out.println(describe(3, 4));
}
}int 7 double 7.5 String seven two ints 7
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05Pass-by-value, בזיכרוןPass-by-value, in memory
המתודה מקבלת עותק של כל ארגומנט. x הוא עותק של 1, ולכן n לא משתנה. arr הוא עותק של ההפניה, ולכן הוא מצביע על אותו מערך כמו a, והשינוי ב-arr[0] נראה גם ב-main. צפו בחצים.
The method gets a copy of every argument. x is a copy of 1, so n doesn't change. arr is a copy of the reference, so it points to the same array as a, and the change to arr[0] shows up in main too. Watch the arrows.
public class Main {
static void change(int x, int[] arr) {
x = 99;
arr[0] = 99;
}
public static void main(String[] args) {
int n = 1;
int[] a = {1, 2, 3};
change(n, a);
System.out.println(n + " " + a[0]);
}
}1 99
צפו בהרצה צעד אחר צעד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
06הצעד של היום בפרויקט מדףToday's step in the Shelf project
כתבו static String card(String title, int year, int stars) שמחזירה Dune (1965) **** (כוכב לכל דירוג), ו-static double average(int a, int b, int c). ב-main הדפיסו שני כרטיסים ואחר כך Average: 3.67 (ממוצע של 4, 3, 4) עם printf.
Write static String card(String title, int year, int stars) returning Dune (1965) **** (a star per point), and static double average(int a, int b, int c). In main print two cards and then Average: 3.67 (the average of 4, 3, 4) with printf.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.