在构造函数中初始化一个静态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屋!
查看全文