非法转发参考Java问题 [英] Illegal forward Reference java issue

查看:68
本文介绍了非法转发参考Java问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释这段代码有什么问题吗

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

如果我注释第1行-一切正常,Base.main方法将显示"1". 如果第1行-未注释,则出现编译时错误:非法前向引用". 因此,据我了解,在静态init块中,我可以为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?

推荐答案

这是因为

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).

因此,例如:如果在i = 1;之后插入int j = i;,则会出现相同的错误.

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

解决此问题的明显方法是在静态初始化块之前声明static int i; .

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

这篇关于非法转发参考Java问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆