【问题标题】:Static Block and Static memory initialization and implementation [duplicate]静态块和静态内存初始化和实现[重复]
【发布时间】:2019-12-29 07:16:25
【问题描述】:

这里我写了java程序

    public class Main {
    static int i=2000;

    public static void main(String[] args) {
        System.out.print("value of j inside main "+j);

    }

    static {
        m1();
        System.out.print("value of i inside static block "+i);
    }


    static void m1() {
        System.out.print("inside static method");
        System.out.print("value of j inside static block "+j);
    }
    static int j =3000;




   }

在静态块中,i的值打印为2000,而j的值不能在静态块中引用? 在 m1() 方法中打印的 j 的值为 0,但是 j 已初始化,那为什么它打印 0? 为什么 j 不能在 static 中引用,而在 m1() 中引用,它首先由 static 块调用? 在main里面,j的值打印为3000? 那么谁能告诉我我在这里理解的问题是什么?

【问题讨论】:

    标签: java static block


    【解决方案1】:

    这是您当前代码的输出:

    inside static method value of j inside static block 0
    value of i inside static block 2000
    value of j inside main 3000
    

    Java 类中的静态块按照它们出现的顺序进行评估。这意味着当调用m1() 方法的静态块执行时,j 还没有被赋值,所以它的值被报告为零。另一方面,i 已经分配了值 2000,因此它会报告您期望的值。

    【讨论】:

      【解决方案2】:

      这是“非法前向引用”,这意味着您试图在定义变量之前使用它。所以你可以在静态块之前移动static int j =3000;

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 2016-08-31
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多