java变量不声明可以直接使用吗_我们可以在不使用Java进行初始化的情况下声明最终变量吗?...

在Java中,final是可与字段类和方法一起使用的access修饰符。当一个方法为final时,它不能被覆盖。

当变量为最终变量时,其值无法进一步修改。

当类结束时,不能扩展。

无需初始化即可声明最终变量

如果稍后声明了最终变量,则无法修改或为其分配值。此外,像实例变量一样,最终变量将不会使用默认值初始化。

因此,必须在声明最终变量后初始化它们。

不过,如果您尝试声明未初始化的最终变量,则会产生编译错误,提示“变量variable_name未在默认构造函数中初始化”

示例

在下面的Java程序中,Student类包含两个最终变量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

要解决此问题,您需要将声明的最终变量初始化为-

示例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、付费专栏及课程。

余额充值