在 Java 中,有多少种方法可以初始化 final 变量?
java 8object oriented programmingprogramming更新于 2025/4/29 13:37:17
在 Java 中,final 是访问修饰符,可用于文件、类和方法。
- 如果方法是 final,则不能被覆盖。
- 如果变量是 final,则其值不能进一步修改。
- 如果类是 final,则不能扩展。
初始化 final 变量
一旦声明 final 变量,就必须对其进行初始化。您可以初始化 final 实例变量 −
- 在声明时为。
public final String name = "Raju"; public final int age = 20;
- 在实例(非静态)块内。
{ this.name = "Raju"; this.age = 20; }
- 在默认构造函数内。
public final String name; public final int age; public Student(){ this.name = "Raju"; this.age = 20; }
注意 − 如果您尝试在其他地方初始化 final 实例变量,则会产生编译时错误。
示例 1:在声明时
在下面的 Java 程序中,Student 类包含两个 final 变量 − name、age 和,我们在声明时初始化它们 −
public class Student { public final String name = "Raju"; public final int age = 20; public void display(){ System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); } public static void main(String args[]) { new Student().display(); } }
输出
Name of the Student: Raju Age of the Student: 20
示例 2:在实例块内
在下面的 Java 程序中,Student 类包含两个 final 变量− name、age 和,我们在实例块内初始化它们 −
public class Student { public final String name; public final int age; { this.name = "Raju"; this.age = 20; } public void display(){ System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); } public static void main(String args[]) { new Student().display(); } }
输出
Name of the Student: Raju Age of the Student: 20
示例 3:在默认构造函数中
在下面的 Java 程序中,Student 类包含两个 final 变量 − name、age 和,我们在默认构造函数中初始化它们 −
public class Student { public final String name; public final int age; public Student(){ this.name = "Raju"; this.age = 20; } public void display(){ System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); } public static void main(String args[]) { new Student().display(); } }
输出
Name of the Student: Raju Age of the Student: 20