在构造函数中初始化一个静态 final 字段 [英] Initialize a static final field in the constructor
本文介绍了在构造函数中初始化一个静态 final 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class A
{
private static final int x;
public A()
{
x = 5;
}
}
final
表示变量只能赋值一次(在构造函数中).static
表示它是一个类实例.final
means the variable can only be assigned once (in the constructor).static
means it's a class instance.
我不明白为什么禁止这样做.这些关键字在什么地方相互干扰?
I can't see why this is prohibited. Where do those keywords interfere with each other?
推荐答案
每次创建类的实例时都会调用一个构造函数.因此,上面的代码意味着每次创建实例时都会重新初始化 x 的值.但是因为变量被声明为final(和static),你只能这样做
A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this
class A {
private static final int x;
static {
x = 5;
}
}
但是,如果您删除静态,则可以这样做:
But, if you remove static, you are allowed to do this:
class A {
private final int x;
public A() {
x = 5;
}
}
或者这个:
class A {
private final int x;
{
x = 5;
}
}
这篇关于在构造函数中初始化一个静态 final 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文