Cannot reference a field before it is * defined" error

落爺英雄遲暮 提交于 2019-12-23 21:10:44

问题


public class Test1 {
 static{
    a=20;  
 //  System.out.println(a); //Line 4
    }
    static int a=getA();

private static int getA() {
    return 10;
}
public static void main(String[] args) {
    System.out.println(a);
}
}

Why it showing error ?but if remove the Line working fine ?


回答1:


It works if you declare a before the static initializer:

public class Test1 {
    static int a=getA();
    static{
        a=20;  
        System.out.println(a);
    }

    private static int getA() {
        return 10;
    }
    public static void main(String[] args) {
        System.out.println(a);
    }
}

Static initialization is done in the order it's written in the code. That means that in your code, you first set a to 20 and then initialize it to getA() - which is just as illegal as if you would have done it inside a function.




回答2:


Order matters.

static fields, block executes based on the order they placed in source code.

Move the declaration up . So that It can available to below blocks.



来源:https://stackoverflow.com/questions/22198527/cannot-reference-a-field-before-it-is-defined-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!