java中的最终变量_有几种方法可以初始化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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值