java final成员 默认值_Java Final变量有默认值吗?

我有一个这样的程序:

class Test {

final int x;

{

printX();

}

Test() {

System.out.println("const called");

}

void printX() {

System.out.println("Here x is " + x);

}

public static void main(String[] args) {

Test t = new Test();

}

}

如果我尝试执行它,我得到编译器错误:变量x可能没有被初始化基于java默认值我应该得到下面的输出正确?

"Here x is 0".

最终变量是否具有dafault值?

如果我改变我的代码这样,

class Test {

final int x;

{

printX();

x = 7;

printX();

}

Test() {

System.out.println("const called");

}

void printX() {

System.out.println("Here x is " + x);

}

public static void main(String[] args) {

Test t = new Test();

}

}

我得到输出:

Here x is 0

Here x is 7

const called

任何人都可以解释这种行为..


版权声明:本文为weixin_35348899原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。