在Java中,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;
}
注-如果尝试在其他地方初始化最终实例变量,则会生成编译时错误。
例1:申报时
在下面的Java程序中,Student类包含两个最终变量-名称,年龄,并且我们在声明时对其进行初始化-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类包含两个最终变量-名称,年龄,我们正在实例块中对其进行初始化-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
Example3:在默认构造函数中
在以下Java程序中,Student类包含两个最终变量-名称,年龄,我们正在默认构造函数中对其进行初始化-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