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

חזרה למפגשBack
JavaJava

static, final וקבועיםstatic, final & constants

מפגש 16: שדות static משותפים, final למשתנים, לשדות ולמחלקות, וקבועים בשמות גדולים.Session 16: Shared static fields, final for variables, fields and classes, and constants in capital letters.

מה נעשה היוםToday's plan

  • מונחיםTerms
  • final: השמה אחת בלבדfinal: one assignment only
  • קבועים ומונה מזהיםConstants and an id counter
  • final על הפניהfinal on a reference
  • טעויות נפוצותCommon mistakes
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

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

  • הפניה final: final int[] a אומר שאי אפשר להצביע עם a על מערך אחר.final reference: final int[] a means a can't be pointed at another array.
  • מספר קסם: מספר שמופיע בקוד בלי הסבר (0.17, 56).magic number: A number in the code with no explanation (0.17, 56).
  • מתודת יצרן: מתודה static שמחזירה עצם חדש, עם שם שמסביר מה מקבלים:factory method: A static method that returns a new object, with a name explaining what you get:
נושאTopic 2

final: השמה אחת בלבדfinal: one assignment only

final: השמה אחת בלבדfinal: one assignment only

  • משתנה final מקבל ערך פעם אחת.A final variable gets a value once.
  • ניסיון לשנות אותו נעצר בקומפילציה.Trying to change it is stopped at compile time.

טעות נפוצהCommon mistake

Main.java · main
final int max = 3;
max = 4;
System.out.println(max);
מה javac עונהWhat javac says
Main.java:4: error: cannot assign a value to final variable max
cannot assign a value to final variable max: max כבר קיבל 3.cannot assign a value to final variable max: max already got 3.
נושאTopic 3

קבועים ומונה מזהיםConstants and an id counter

קבועים ומונה מזהיםConstants and an id counter

  • MIN_RATING ו-MAX_RATING הם קבועים של המחלקה.MIN_RATING and MAX_RATING are class constants.
  • count הוא מונה static אחד, ו-id הוא שדה final של כל ספר, שנקבע פעם אחת בבנאי.count is one static counter, and id is a final field of each book, set once in the constructor.
  • בזיכרון: Book.count ב-static, ו-id בתוך כל עצם.In memory: Book.count under static, and id inside each object.
נושאTopic 4

final על הפניהfinal on a reference

final על הפניה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.
נושאTopic 5

טעויות נפוצותCommon mistakes

טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

  • cannot assign a value to final variable count:cannot assign a value to final variable count:

טעות נפוצהCommon mistake

Main.java · main
final int count = 0;
for (int i = 1; i <= 10; i++) {
    if (i % 3 == 0) {
        count++;
    }
}
System.out.println(count);
מה javac עונהWhat javac says
Main.java:6: error: cannot assign a value to final variable count
cannot 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.
נושאTopic 6

פרויקט מדףShelf project

הצעד של היום בפרויקט מדףToday's step in the Shelf project

  • מדף, צעד 16: מונה ספרים וקבועי דירוגShelf, step 16: a book counter and rating constants

הפניה final: final int[] a אומר שאי אפשר להצביע עם a על מערך אחר.final reference: final int[] a means a can't be pointed at another array.

מספר קסם: מספר שמופיע בקוד בלי הסבר (0.17, 56).magic number: A number in the code with no explanation (0.17, 56).

מתודת יצרן: מתודה static שמחזירה עצם חדש, עם שם שמסביר מה מקבלים:factory method: A static method that returns a new object, with a name explaining what you get:

משתנה final מקבל ערך פעם אחת.A final variable gets a value once.

ניסיון לשנות אותו נעצר בקומפילציה.Trying to change it is stopped at compile time.

MIN_RATING ו-MAX_RATING הם קבועים של המחלקה.MIN_RATING and MAX_RATING are class constants.

count הוא מונה static אחד, ו-id הוא שדה final של כל ספר, שנקבע פעם אחת בבנאי.count is one static counter, and id is a final field of each book, set once in the constructor.

בזיכרון: Book.count ב-static, ו-id בתוך כל עצם.In memory: Book.count under static, and id inside each object.

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.

cannot assign a value to final variable count:cannot assign a value to final variable count:

מדף, צעד 16: מונה ספרים וקבועי דירוגShelf, step 16: a book counter and rating constants

final int[] a = {1, 2}; מה מהבאים יתקמפל?final int[] a = {1, 2}; Which of these compiles?

  • a[0] = 5;a[0] = 5;
  • a = new int[2];a = new int[2];
  • a = null;a = null;
  • אף אחדNone

a[0] = 5;a[0] = 5;

איך נהוג לכתוב קבוע של מחלקה?How is a class constant usually written?

  • static final int MAX_RATING = 5;static final int MAX_RATING = 5;
  • final int maxRating = 5;final int maxRating = 5;
  • const int MAX = 5;const int MAX = 5;
  • static int MAX = 5;static int MAX = 5;

static final int MAX_RATING = 5;static final int MAX_RATING = 5;

String היא final class. מה זה אומר?String is a final class. What does that mean?

  • אי אפשר ליצור ממנה עצמיםYou can't create objects of it
  • אי אפשר לרשת ממנהYou can't extend it
  • כל השדות שלה publicAll its fields are public
  • אי אפשר לשנות משתנה מסוג StringA String variable can't change

אי אפשר לרשת ממנהYou can't extend it

עובר או נכשלPass or fail

  • מחלקה Grade עם קבועים PASS = 56 ו-MAX = 100, ו-static String result(int score) שמחזירה pass, fail או invalid (מחוץ ל-0 עד MAX).A class Grade with constants PASS = 56 and MAX = 100, and static String result(int score) returning pass, fail or invalid (outside 0 to MAX).

צייד באגים: מונה שאסור לו לזוזBug hunter: a counter that can't move

  • התוכנית סופרת כמה מספרים מ-1 עד 10 מתחלקים ב-3, ולא מתקמפלת.The program counts how many numbers from 1 to 10 divide by 3, and doesn't compile.

כרטיסים ממוספריםNumbered tickets

  • מחלקה Ticket עם private static int nextId = 1, ושדות private final int id ו-private final String owner.A class Ticket with private static int nextId = 1, and fields private final int id and private final String owner.

בלי מספרי קסםNo magic numbers

ימי השבועDays of the week

  • מחלקה Week עם הקבוע static final String[] DAYS (Sun עד Sat) ו-static String dayName(int day) (1 עד 7, אחרת זורקת day must be 1-7, got 8).A class Week with the constant static final String[] DAYS (Sun to Sat) and static String dayName(int day) (1 to 7, otherwise it throws day must be 1-7, got 8).

מדף, צעד 16: מונה ספרים וקבועי דירוגShelf, step 16: a book counter and rating constants

  • ל-Book יש MIN_RATING ו-MAX_RATING, מונה private static int count, ו-private final int id.Book has MIN_RATING and MAX_RATING, a counter private static int count, and private final int id.

מתודות יצרןFactory methods

מחלקת עזר אמיתיתA real utility class

  • final class TextUtil עם בנאי private ריק (כדי שאיש לא ייצור ממנה עצם), ושתי מתודות static:final class TextUtil with an empty private constructor (so nobody makes an object of it), and two static methods:

מה למדנוWhat we learned

  • הפניה final: final int[] a אומר שאי אפשר להצביע עם a על מערך אחר.final reference: final int[] a means a can't be pointed at another array.
  • משתנה final מקבל ערך פעם אחת.A final variable gets a value once.
  • MIN_RATING ו-MAX_RATING הם קבועים של המחלקה.MIN_RATING and MAX_RATING are class constants.
  • 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.
  • cannot assign a value to final variable count:cannot assign a value to final variable count:
  • מדף, צעד 16: מונה ספרים וקבועי דירוגShelf, step 16: a book counter and rating constants

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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