[英]Final non-static data member
如果不允许两次初始化final
非static
数据成员,那么如何在下面的示例中将x
设置为所需的值?
class Temp6
{
final int x;
Temp6()
{
System.out.println(this.x);
this.x=10;
}
public static void main(String[]s)
{
Temp6 t1 = new Temp6();
System.out.println(t1.x);
}
}
Java默认情况下将x
的值设置为0
,那么如何将其更改为10
?
在Java中标记为final
的变量只能初始化一次。
只是简单地宣称x
与final int x;
不初始化它。 因此,在Temp6
构造函数中分配给x
是合法的。 但是,您将无法在构造x
之后为x
分配其他值。
也就是说,以下是对t1.x
的赋值:
public static void main(String[] s) {
Temp6 t1 = new Temp6();
t1.x = 11; // ERROR
}
是不合法的。
在类构造函数中初始化最终变量。
public class Blam
{
private final int qbert;
public Blam(int qbertValue)
{
qbert = qbertValue;
}
}
在代码中读取this.x
应该会出错,因为final
变量不会在声明时初始化。 t1.x
应该为10
因为x
肯定在唯一构造函数的末尾分配。
您必须在构造函数中交换两行代码才能进行编译,那里将是10行。
class Temp {
int x; // declaration and definition; defaulted to 0
final int y; // declaration, not initialized
Temp() {
System.out.println(x); // prints 0
x = 1;
System.out.println(x); // prints 1
x = 2; // last value, instance.x will give 2
System.out.println(y); // should be a compiler error: The blank final field y may not have been initialized
y = 3; // definite assignment, last and only value, instance.y will be 3 whereever used
System.out.println(y); // prints 3
y = 4; // compile error: The final field y may already have been assigned
}
}
我以前从未想过,这里很有趣。 最终字段变量的行为类似于方法中的局部变量 ,必须在使用前对其进行显式赋值 (确定赋值很难形式化,请参阅JLS参考,但这很合逻辑)。
如果要从外部为x
赋值,可以这样进行:
public class Temp {
private final int x;
public Temp(int x) {
this.x = x;
}
public int getX() { return this.x; }
public static void main(String[] args) {
Temp temp = new Temp(10);
System.out.println(temp.getX()); // 10
}
}
final
变量是java常量。 它们应该在类加载之前初始化。
final int x=10;
如果您的最终变量是静态的,则不必像在声明本身中给出值一样,则可以使用-
class Demo {
static final int x;
static {
x = 10;
}
}
在类加载时,静态块仅执行一次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.