相关疑难解决方法(0)

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

如果我尝试执行它,我收到编译器错误:variable x might not have been initialized基于java默认值我应该得到以下输出权?

"Here x is 0".
Run Code Online (Sandbox Code Playgroud)

最终变量是否具有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); …
Run Code Online (Sandbox Code Playgroud)

java final

78
推荐指数
3
解决办法
1万
查看次数

标签 统计

final ×1

java ×1