java什么是最终变量_什么是空白最终变量?什么是Java中的静态空白最终变量?...

静态变量-静态变量也称为类变量。您可以使用关键字声明一个静态变量。一旦声明了一个静态变量,则无论在该类中创建了多少个对象,在类中都只有一个副本。public static int num = 39;

实例变量-这些变量属于类的实例(对象)。这些在类内但在方法外声明。这些在实例化类时初始化。可以从该特定类的任何方法,构造函数或块中访问它们。

您必须使用对象访问实例变量。也就是说,要访问实例变量,您需要创建该类的对象,并使用该对象,您需要访问这些变量。

final-声明变量final后,您将无法为它重新赋值。

空白变量

没有初始化的最终变量称为空白最终变量。与实例变量一样,最终变量将不会使用默认值初始化。因此,在声明最终变量后必须初始化它们。

但是,如果您尝试在代码中使用空变量,则会生成编译时错误。

示例

在下面的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

静态空白最终变量

以同样的方式,如果您声明了一个静态变量final而不对其进行初始化,则将其视为静态最终变量。

当变量被声明为静态变量和最终变量时,您只能在静态块中对其进行初始化,如果您尝试在其他位置对其进行初始化,则编译器会假定您正在尝试将值重新分配给它并生成编译时错误-

示例class Data{

static final int num;

Data(int i){

num = i;

}

}

public class ConstantsExample {

public static void main(String args[]) {

System.out.println("value of the constant: "+Data.num);

}

}

编译时错误ConstantsExample.java:4: error: cannot assign a value to final variable num

num = i;

^

1 error

示例

因此,必须在静态块中初始化静态最终变量。

为了使上述程序正常工作,您需要将静态块中的最终静态变量初始化为-class Data{

static final int num;

static{

num = 1000;

}

}

public class ConstantsExample {

public static void main(String args[]) {

System.out.println("value of the constant: "+Data.num);

}

}

输出结果value of the constant: 1000

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值