“Constant” fields are defined using the final keyword, indicating their values can be assigned only once.
![]() | Important |
|---|---|
Declaring a reference variable as |
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;
…
}
}
با استفاده از علامت dot(.) در جاوا می توانیم متدهای یک object را Invoke کنیم:
به عنوان مثال:
objectRef.method(params)
اگر در کل پروژه متدهای مورد نظر را متد Static بنویسیم و متدهای static همدیگر را call کنند دیگر نیازی به استفاده از هیچ Object ای نیست و این پروژه یک پروژه ی Procedural است و Object Oriented نیست. با این روش جاوا نوشتن برنامه های Procedural را نیز مهیا ساخته است.