หากคุณประกาศตัวแปรแบบคงที่และแบบสุดท้าย คุณต้องเริ่มต้นตัวแปรนั้นเมื่อประกาศหรือในบล็อกแบบสแตติก หากคุณพยายามที่จะเริ่มต้นใน Constructor คอมไพเลอร์จะถือว่าคุณกำลังพยายามกำหนดค่าให้กับมันและสร้างข้อผิดพลาดเวลาคอมไพล์ -
ตัวอย่าง
class Data {
static final int num;
Data(int i) {
num = i;
}
}
public class ConstantsExample {
public static void main(String args[]) {
System.out.println("value of the constant: "+Data.num);
}
} ข้อผิดพลาดในการคอมไพล์เวลา
ConstantsExample.java:4: error: cannot assign a value to final variable num num = i; ^ 1 error
เพื่อให้โปรแกรมนี้ทำงานได้ คุณต้องเริ่มต้นตัวแปรสแตติกสุดท้ายในบล็อกสแตติกเป็น −
ตัวอย่าง
class Data {
static final int num;
static {
num = 1000;
}
}
public class ConstantsExample {
public static void main(String args[]) {
System.out.println("value of the constant: "+Data.num);
}
} ผลลัพธ์
value of the constant: 1000