Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

Illegal forward Reference java issue

Could anyone explain what is wrong with this code:

    public class Base {


    static {
        i = 1;
        System.out.println("[Base]after static init block i=" + i);// LINE 1
        System.out.println("*************************************");
        System.out.println();
    }
    static int i;



    public static void main(String[] args) {
        System.out.println(Base.i);
    }
}

If I comment LINE 1 - everything is OK and Base.main method prints "1". If LINE 1 - is not commented, got compile time error: "illegal forward reference". So, as i understand in static init block I can set value for i, but not read. Could anyone explain why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because of the restrictions on the use of Fields during Initialization. In particular, the use of static fields inside a static initialization block before the line on which they are declared can only be on the left hand side of an expression (i.e. an assignment), unless they are fully qualified (in your case Base.i).

So for example: if you insert int j = i; right after i = 1; you would get the same error.

The obvious way to solve the issue is to declare static int i; before the static initialization block.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...