Không. Chỉ dùng final không đủ để tạo constant theo định nghĩa chuẩn (một bản sao duy nhất cho toàn chương trình).
Tại sao cần cả static và final?
- static: Biến thuộc về class, load lúc compile time → chỉ có 1 bản sao chung cho tất cả instance.
- final: Giá trị không thể thay đổi sau khi gán.
Kết hợp static final mới tạo ra constant thực sự.
Ví dụ Constant đúng chuẩn
class Data {
static final int INTEGER_CONSTANT = 20;
static final String STRING_CONSTANT = "hello";
static final float FLOAT_CONSTANT = 1654.22f;
static final char CHAR_CONSTANT = 'C';
}
public class ConstantsExample {
public static void main(String args[]) {
System.out.println("value of integerConstant: " + Data.INTEGER_CONSTANT);
System.out.println("value of stringConstant: " + Data.STRING_CONSTANT);
System.out.println("value of floatConstant: " + Data.FLOAT_CONSTANT);
System.out.println("value of characterConstant: " + Data.CHAR_CONSTANT);
}
}
value of integerConstant: 20 value of stringConstant: hello value of floatConstant: 1654.22 value of characterConstant: C
Nếu chỉ dùng final (không static)
class Data {
final int integerConstant = 20; // Instance final variable
}
public class ConstantExample {
public static void main(String args[]) {
Data obj1 = new Data();
Data obj2 = new Data();
System.out.println("obj1: " + obj1.integerConstant); // 20
System.out.println("obj2: " + obj2.integerConstant); // 20 - nhưng là 2 bản sao riêng!
}
}
Mặc dù giá trị giống nhau, nhưng mỗi object có một bản sao riêng biệt của biến này. Điều này vi phạm định nghĩa constant (chỉ 1 bản sao).
Kết luận
Để tạo constant đúng chuẩn trong Java: static final <type> CONSTANT_NAME = value;. Tên constant theo convention: UPPER_SNAKE_CASE.