เมื่อคุณประกาศตัวแปรขั้นสุดท้าย หลังจากเริ่มต้นแล้ว คุณจะไม่สามารถแก้ไขค่าของตัวแปรเพิ่มเติมได้อีก ยิ่งไปกว่านั้น เช่นเดียวกับตัวแปรอินสแตนซ์ ตัวแปรสุดท้ายจะไม่ถูกเริ่มต้นด้วยค่าเริ่มต้น
ดังนั้น จึงจำเป็นต้องเริ่มต้นตัวแปรสุดท้ายเมื่อคุณประกาศ . ถ้าไม่ใช่เวลาคอมไพล์จะเกิดข้อผิดพลาด
ตัวอย่าง
public class FinalExample {
final int j;
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.j);
}
} ข้อผิดพลาดในการคอมไพล์
FinalExample.java:5: error: non-static variable j cannot be referenced from a static context System.out.println(j); ^ 1 error
การเริ่มต้นตัวแปรสุดท้าย
คุณสามารถเริ่มต้นตัวแปรสุดท้ายได้ 4 วิธี -
ขณะประกาศ
public class FinalExample {
final int j = 100;
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.j);
}
} ผลลัพธ์
100
ใช้วิธีสุดท้าย
import java.util.Scanner;
public class FinalExample {
final int num = getNum();
public static final int getNum() {
System.out.println("Enter the num value");
return new Scanner(System.in).nextInt();
}
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.num);
}
} ผลลัพธ์
Enter the num value 20 20
การใช้ตัวสร้าง
public class FinalExample {
final int num;
public FinalExample(int num) {
this.num = num;
}
public static void main(String args[]){
FinalExample obj = new FinalExample(20);
System.out.println(obj.num);
}
} ผลลัพธ์
20
การใช้บล็อกการเริ่มต้นอินสแตนซ์
public class FinalExample {
final int num; {
num = 500;
}
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.num);
}
} ผลลัพธ์
500
ยกเว้นในกรณีที่เป็นเมธอดสุดท้าย หากคุณเริ่มต้นตัวแปรสุดท้ายในสามวิธีที่เหลือ ตัวแปรจะถูกเริ่มต้นในไม่ช้า คุณจะสร้างคลาสของตัวแปรนั้น