在Java中,我们可以在不初始化的情况下声明final变量吗?
在Java中,**final** 是一个访问修饰符,可以用于字段、类和方法。
- 当一个方法是final时,它不能被重写。
- 当一个变量是final时,它的值不能被进一步修改。
- 当一个类是final时,它不能被扩展。
在不初始化的情况下声明final变量
如果你声明了一个final变量,之后你不能修改或为其赋值。此外,与实例变量不同,final变量不会用默认值初始化。
因此,*必须在声明final变量后立即对其进行初始化*。
但是,如果你尝试在不初始化的情况下声明final变量,则会生成一个编译错误,提示“变量variable_name在默认构造函数中未初始化”。
示例
在下面的Java程序中,Student类包含两个final变量name和age,并且它们没有被初始化。
public class Student {
public final String name;
public final int age;
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();
}
}编译时错误
编译时,此程序会生成以下错误。
输出
Student.java:3: error: variable name not initialized in the default constructor private final String name; ^ Student.java:4: error: variable age not initialized in the default constructor private final int age; ^ 2 errors
为了解决这个问题,你需要初始化声明的final变量,如下所示:
示例
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP