java:访问静态块内的静态变量 [英] java : accessing static variables inside static block

查看:362
本文介绍了java:访问静态块内的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分析以下静态块中的一些奇怪场景:

Analyzing some weird scenario in following static block :

static {
  System.out.println("Inside Static Block");
  i=100; // Compilation Successful , why ?
  System.out.println(i); // Compilation error "Cannot reference a field before it is defined"
}

private static int i=100;

虽然相同的代码在使用时工作正常:

While same code is working fine while using :

static {
  System.out.println("Inside Static Block");
  i=100; // Compilation Successful , why ?
  System.out.println(MyClass.i); // Compiles OK
}

private static int i=100;

在SOP要求时,不确定为什么变量初始化不需要使用类名进行变量访问?

Not sure why variable initialization do not need variable access using class name while SOP requires ?

推荐答案

这是因为初始化期间使用字段的限制。特别是,在声明它们的行之前在静态初始化块中使用静态字段只能在表达式的左侧(即赋值),除非它们是完全限定的(在您的情况下<$ c) $ c> MyClass.i )。

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

例如:如果你插入 int j = i; i = 100之后; 你会得到同样的错误。

So for example: if you insert int j = i; right after i = 100; 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天全站免登陆