static, final וקבועיםstatic, final & constants
שדות static משותפים, final למשתנים, לשדות ולמחלקות, וקבועים בשמות גדולים.
Shared static fields, final for variables, fields and classes, and constants in capital letters.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- הפניה final:
final int[] aאומר שאי אפשר להצביע עםaעל מערך אחר. את התוכן של המערך עדיין אפשר לשנות.final reference:final int[] ameansacan't be pointed at another array. The array's contents can still change. - מספר קסם: מספר שמופיע בקוד בלי הסבר (
0.17,56). קבוע עם שם (VAT,PASS) מסביר את עצמו ומשתנה במקום אחד.magic number: A number in the code with no explanation (0.17,56). A named constant (VAT,PASS) explains itself and changes in one place. - מתודת יצרן: מתודה static שמחזירה עצם חדש, עם שם שמסביר מה מקבלים:
Temperature.ofCelsius(100). לעתים קרובות הבנאי עצמו private.factory method: A static method that returns a new object, with a name explaining what you get:Temperature.ofCelsius(100). Often the constructor itself is private.
02final: השמה אחת בלבדfinal: one assignment only
משתנה final מקבל ערך פעם אחת. ניסיון לשנות אותו נעצר בקומפילציה.
A final variable gets a value once. Trying to change it is stopped at compile time.
final: השמה אחת בלבד
final: one assignment only
public class Main {
public static void main(String[] args) {
final int max = 3;
max = 4;
System.out.println(max);
}
}Main.java:4: error: cannot assign a value to final variable max
max = 4;
^
1 errorcannot assign a value to final variable max: max כבר קיבל 3.cannot assign a value to final variable max: max already got 3.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03קבועים ומונה מזהיםConstants and an id counter
MIN_RATING ו-MAX_RATING הם קבועים של המחלקה. count הוא מונה static אחד, ו-id הוא שדה final של כל ספר, שנקבע פעם אחת בבנאי. בזיכרון: Book.count ב-static, ו-id בתוך כל עצם.
MIN_RATING and MAX_RATING are class constants. count is one static counter, and id is a final field of each book, set once in the constructor. In memory: Book.count under static, and id inside each object.
public class Main {
public static void main(String[] args) {
Book a = new Book("Dune", 5);
Book b = new Book("Emma", 4);
System.out.println(a.getId() + " " + b.getId() + " of " + Book.getCount());
}
}
class Book {
static final int MIN_RATING = 1;
static final int MAX_RATING = 5;
private static int count = 0;
private final int id;
private final String title;
private final int rating;
Book(String title, int rating) {
if (rating < MIN_RATING || rating > MAX_RATING) {
throw new IllegalArgumentException("bad rating " + rating);
}
count++;
this.id = count;
this.title = title;
this.rating = rating;
}
int getId() {
return id;
}
static int getCount() {
return count;
}
}1 2 of 2
צפו בהרצה צעד אחר צעד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
04final על הפניהfinal on a reference
final int[] scores נועל את החץ, לא את המערך: scores[0] = 95 מותר, אבל scores = new int[3] היה נעצר בקומפילציה.
final int[] scores locks the arrow, not the array: scores[0] = 95 is allowed, but scores = new int[3] would be stopped at compile time.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
final int[] scores = {70, 80};
scores[0] = 95;
System.out.println(Arrays.toString(scores));
}
}[95, 80]
צפו בהרצה צעד אחר צעד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
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 counter that can't move
public class Main {
public static void main(String[] args) {
final int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
count++;
}
}
System.out.println(count);
}
}Main.java:6: error: cannot assign a value to final variable count
count++;
^
1 errorcannot assign a value to final variable count: מונה חייב להשתנות, ולכן הוא לא יכול להיות final.cannot assign a value to final variable count: a counter must change, so it can't be final.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06הצעד של היום בפרויקט מדףToday's step in the Shelf project
ל-Book יש MIN_RATING ו-MAX_RATING, מונה private static int count, ו-private final int id. הבנאי בודק את הדירוג לפני שהוא סופר. צרו את Dune (5), Emma (4) ו-Ulysses (9), כל אחד ב-try משלו, והדפיסו #1 Dune (5), #2 Emma (4), Error: Rating must be 1-5, got 9, Books: 2.
Book has MIN_RATING and MAX_RATING, a counter private static int count, and private final int id. The constructor checks the rating before counting. Create Dune (5), Emma (4) and Ulysses (9), each in its own try, and print #1 Dune (5), #2 Emma (4), Error: Rating must be 1-5, got 9, Books: 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.