有几种方法可以初始化Java中的最终变量?
在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
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练