如果不允许两次初始化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
?
发布于 2014-07-29 17:52:01
在Java中标记为final
的变量只能初始化一次。
简单地用final int x;
声明x
并不能初始化它。因此,在Temp6
构造函数中为x
赋值是合法的。但是,您不能在构造函数之后为x
分配不同的值。
也就是说,在以下内容中对t1.x
的赋值:
public static void main(String[] s) {
Temp6 t1 = new Temp6();
t1.x = 11; // ERROR
}
是不合法的。
发布于 2014-07-29 18:37:50
在类构造函数中初始化最终变量。
public class Blam
{
private final int qbert;
public Blam(int qbertValue)
{
qbert = qbertValue;
}
}
发布于 2014-07-29 18:55:14
在代码中读取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
}
}
我以前从来没有想过这一点,这里很有趣。Final field variables的行为类似于local variables in methods,它们在使用之前必须是explicitly 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
}
}
https://stackoverflow.com/questions/25021744
复制