静态变量的奇怪行为

时间:2015-04-07 11:18:58

标签: java

我上课AbstractsAndInterfaces

public static AbstractsAndInterfaces instance = new AbstractsAndInterfaces();
private static final int DELTA = 5;

private static int BASE = 7;

private int x;
public AbstractsAndInterfaces()
{
    //System.out.println(BASE);
    //System.out.println(DELTA);
    x = BASE + DELTA;
}
public static int getBASE()
{
    return BASE;
}

   /**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    System.out.println(AbstractsAndInterfaces.instance.x);
}

为什么打印5?

为什么BASE变量未初始化?

1 个答案:

答案 0 :(得分:10)

那是因为:

private static final int DELTA = 5;将是编译时常量。因此,当类初始化(一旦加载)后,5将已经可用(初始化)。

执行的第一行是: public static AbstractsAndInterfaces instance = new AbstractsAndInterfaces();

所以,现在你将去:

public AbstractsAndInterfaces()
{
    //System.out.println(BASE);
    //System.out.println(DELTA);
    x = BASE + DELTA; // same as x= 0+5 i.e default value of fields + constant value 5
}

在上面的代码中,DELTA将为5,但BASE将为0,因为它不是final。将BASE更改为最终版会将结果更改为12

编辑:

用于显示具有字节代码的OP场景的示例代码。

public class Sample {
    static Sample s = new Sample();
    static final int x = 5;
    static int y = 10;

    public Sample() {
        int z = x + y;
        System.out.println(z);
    }

    public static void main(String[] args) {

    }

}

在上面的代码中,当程序运行时,输出将是5而不是10。现在让我们看一下字节码

构造函数的字节代码如下所示:

P

ublic Sample();
   descriptor: ()V
   flags: ACC_PUBLIC
   Code:
     stack=2, locals=2, args_size=1
        0: aload_0
        1: invokespecial #24                 // Method java/lang/Object."<init>
:()V 
        4: iconst_5       ------->           // Here 5 is used directly as it is a compile time constant
        5: getstatic     #20   ------->      // Field y:I
        8: iadd
        9: istore_1
       10: getstatic     #25                 // Field java/lang/System.out:Ljav
/io/PrintStream;
       13: iload_1
       14: invokevirtual #31                 // Method java/io/PrintStream.prin
ln:(I)V
       17: return

静态初始化块的字节代码:

static {};     descriptor :()V     flags:ACC_STATIC     码:       stack = 2,locals = 0,args_size = 0          0:新#1 //类样本          3:重复          4:invokespecial#15 //方法“”:()V          7:putstatic#18 // Field s:LSample;         10:bipush 10         12:putstatic#20 // Field y:我         15:回归       LineNumberTable:         第3:0行         第5:10行         第1:15行       LocalVariableTable:         开始长度插槽名称签名

如果仔细检查,x未在类的静态init中初始化。仅设置了y,因为它是静态的。但是当你查看构造函数时,你会看到常量5被直接使用(iconst_5)并被压入堆栈。

现在,如果您在main()中添加以下代码:

public static void main(String[] args) {
    System.out.println(Sample.x);
    System.out.println(Sample.y);
}

main()的字节代码为:

   public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=1, args_size=1
         0: getstatic     #25                 // Field java/lang/System.out:Ljav
a/io/PrintStream;
         3: iconst_5 -->                      // No "x" but a constant value instead of "x"
         4: invokevirtual #31                 // Method java/io/PrintStream.prin
tln:(I)V
         7: getstatic     #25                 // Field java/lang/System.out:Ljav
a/io/PrintStream;
        10: getstatic     #20                 // Field y:I --> but "y" is being fetched
        13: invokevirtual #31                 // Method java/io/PrintStream.prin
tln:(I)V
        16: return
      LineNumberTable:
        line 13: 0
        line 14: 7
        line 15: 16
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      17     0  args   [Ljava/lang/String;
}

再次注意x被用作iconst_5,而y获取/推荐间接使用。