در مورد Constants و یا به عبارتی دیگر Final در جاوا

  • “Constant” fields are defined using the final keyword, indicating their values can be assigned only once.

    • Final instance fields must be initialized by the end of object construction.
    • Final static fields must be initialized by the end of class initialization.
    • Final local variables must be initialized only once before they are used.
    • Final method parameters are initialized on the method call.
[Important]Important

Declaring a reference variable as final means only that once initialized to refer to an object, it can’t be changed to refer to another object. It does not imply that the state of the object referenced cannot be changed.

  • Final static field can be initialized through direct assignment or by using a static initializer.

    • A static initializer consists of the keyword static followed by a block, for example:

      private static int[] values = new int[10];
      static {
          for (int i = 0; i < values.length; i++) {
              values[i] = (int) (100.0 * Math.random());
          }
      }

If we declare ssn as final, we then must either assign it right away or initialize it in all constructors. This can also be done indirectly via constructor-to-constructor calls. Once initialized, final instance fields (e.g. ssn) can no longer be changed.

class Employee {
    final String ssn;
    …
    Employee(String ssn) {
        this.ssn = ssn;
    }
    …
}

Local variables can also be set as final, to indicate that they should not be changed once set:

public class EmployeeDemo {
    public static void main(String[] args) {
        final Employee e1 = new Employee(…);
        final Employee e2 = new Employee("456-78-901", 1974);
        final Employee e3;
        e3 = e2;
        …
    }
}

نظرات 0 + ارسال نظر
برای نمایش آواتار خود در این وبلاگ در سایت Gravatar.com ثبت نام کنید. (راهنما)
ایمیل شما بعد از ثبت نمایش داده نخواهد شد