简体   繁体   English

java中的静态变量初始化

[英]Static variable initialization in java

Consider the following code :考虑以下代码:

  public class TestClass 
    {
      int j=10;
      static int h=j;

      TestClass()
      {

          System.out.println(h);
      }

      public static void main(String[] args)
      {
          TestClass obj= new TestClass();       


      }

    }

Why this generates error even when i have already declared j above h .为什么即使我已经在 h 之上声明了 j 也会产生错误。

The error is because you are mixing static declarations with instance variable declarations (which is pretty clear from the error message Cannot make a static reference to the non-static field j ).错误是因为您将静态声明与实例变量声明混合在一起(从错误消息Cannot make a static reference to the non-static field j 中可以清楚地看出这一点)。 Change the first initialization to将第一次初始化更改为

static int j = 10;

and your code compiles just fine.你的代码编译得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM