在Java中,初始化final变量有多少种方法?
在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP