Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Biến final tĩnh và không tĩnh rỗng (blank final) trong Java


Biến static: Khai báo với từ khóa static, còn gọi là biến lớp. Định nghĩa trong constructor hoặc ngoài hàm lớp. Khi biến static, nó chia sẻ giữa tất cả đối tượng của lớp, bất kể số đối tượng tạo ra.

Minh họa từ khóa static với biến:

Ví dụ

public class Demo{    String name;    static String designation;    public void display_data(){       System.out.println("The name is: " + name);       System.out.println("The designation of this team members is : " + designation);    }    public static void main(String s[]){       Demo.designation = "Intern";       Demo my_obj = new Demo();       my_obj.name = "Joe";       Demo my_obj_2 = new Demo();       my_obj_2.name = "Joanna";       my_obj.display_data();       my_obj_2.display_data();       my_obj.designation = "Senior dev";       System.out.println("\nAfter the changes, the data is :\n");       my_obj.display_data();       my_obj_2.display_data();    } }

Kết quả

The name is: Joe The designation of this team members is : Intern The name is: Joanna The designation of this team members is : Intern After the changes, the data is : The name is: Joe The designation of this team members is : Senior dev The name is: Joanna The designation of this team members is : Senior dev

Lớp Demo chứa biến và hàm display_data hiển thị biến lớp. Trong main, thể hiện lớp tạo, gán tên và chức danh cho biến đối tượng. Hiển thị và tạo đối tượng khác làm tương tự. Dữ liệu hiển thị. Thay đổi phản ánh ở đây.

Biến static final rỗng - Cùng định nghĩa biến final rỗng cùng từ khóa static, nghĩa là chỉ có thể khởi tạo trong khối static code.

Biến final rỗng (Blank final variable) - Theo tên, biến final không có giá trị gán gọi là blank final variable. Chỉ khởi tạo trong constructor, không khởi tạo gây lỗi compile.

Hoạt động của blank final variable:

Ví dụ

public class Demo{    private static final int val_1;    private final int val_2;    static{ val_1 = 1;    }    Demo(int val_3){       val_2 = val_3;    }    public static void main(String s[]){       Demo obj_1 = new Demo(95);       Demo obj_2 = new Demo(99);       System.out.println("The value of first variable is : ");       System.out.println(Demo.val_1);       System.out.println("The value of first variable accessed using the object : ");       System.out.println(obj_1.val_2);    } }

Kết quả

The value of first variable is : 1 The value of first variable accessed using the object : 95

Lớp Demo chứa biến và constructor Demo gán giá trị cho biến lớp. Trong main, hai thể hiện lớp tạo và giá trị hiển thị trên console.