日期:2014-05-20  浏览次数:20749 次

关于static的用法
public   class   Test   {
public   static   int   i=100;
public   static   void   main(String[]   args)   {
Test   t=new   Test();
t=null;//已经将t指向空
System.out.println(t.i);//为什么这里i还可以打印100?
}
}

对于上面的问题,思考后还是不明白为什么,请高手指点?静态变量、方法在内存中到底是怎么理解?机制是怎么样的?谢谢。

------解决方案--------------------
...还是讲清楚点吧
对你的程序稍微加了点东西.
public class Test {
public static int i=100;
public int j = 90;
public static void main(String[] args) {
Test t=new Test();
t=null;//已经将t指向空
System.out.println(Test.i);
System.out.println(t.i);//为什么这里i还可以打印100?
System.out.println(t.j);
}
}

以下是执行javap -verbose Test后的结果.
Compiled from "Test.java "
public class Test extends java.lang.Object
SourceFile: "Test.java "
minor version: 0
major version: 50
Constant pool:
const #1 = Method #8.#21; // java/lang/Object. " <init> ":()V
const #2 = Field #3.#22; // Test.j:I
const #3 = class #23; // Test
const #4 = Method #3.#21; // Test. " <init> ":()V
const #5 = Field #24.#25; // java/lang/System.out:Ljava/io/PrintS
tream;
const #6 = Field #3.#26; // Test.i:I
const #7 = Method #27.#28; // java/io/PrintStream.println:(I)V
const #8 = class #29; // java/lang/Object
const #9 = Asciz i;
const #10 = Asciz I;
const #11 = Asciz j;
const #12 = Asciz <init> ;
const #13 = Asciz ()V;
const #14 = Asciz Code;
const #15 = Asciz LineNumberTable;
const #16 = Asciz main;
const #17 = Asciz ([Ljava/lang/String;)V;
const #18 = Asciz <clinit> ;
const #19 = Asciz SourceFile;
const #20 = Asciz Test.java;
const #21 = NameAndType #12:#13;// " <init> ":()V
const #22 = NameAndType #11:#10;// j:I
const #23 = Asciz Test;
const #24 = class #30; // java/lang/System
const #25 = NameAndType #31:#32;// out:Ljava/io/PrintStream;
const #26 = NameAndType #9:#10;// i:I
const #27 = class #33; // java/io/PrintStream
const #28 = NameAndType #34:#35;// println:(I)V
const #29 = Asciz java/lang/Object;
const #30 = Asciz java/lang/System;
const #31 = Asciz out;
const #32 = Asciz Ljava/io/PrintStream;;
const #33 = Asciz java/io/PrintStream;
const #34 = Asciz println;
const #35 = Asciz (I)V;

{
public static int i;

public int j;

public Test();
Code:
Stack=2, Locals=1, Args_size=1
0: aload_0
1: invokespecial #1; //Method java/lang/Object. " <init> ":()V
4: aload_0
5: bipush 90
7: putfield #2; //Field j:I
10: return
LineNumberTable:
line 1: 0
line 3: 4


public static void main(java.lang.String[]);
Code:
Stack=2, Locals=2, Args_size=1
0: new #3; //class Test
3: dup
4: invokespecial #4; //Method " <init> ":()V
7: astore_1
8: aconst_null
9: astore_1
10: getstatic #5; //Field java/lang/System.out:Ljava/io/PrintStream;
13: getstatic #6; //Field i:I
16: invokevirtual #7; //Method java/io/PrintStream.println:(I)V
19: getstatic #5; //Field java/lang/System.out:Ljava/io/PrintStream;
22: aload_1
23: pop