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

static域被继承的后,子类和父类一起执行,这块代码只被执行一次。为什么?

public   class   Test   {
        public   static   void   main(String[]   args)   {
                A   a   =   new   B();//   标记1
                System.out.println( "============================= ");
                B   b   =   new   B();
        }
}

abstract   class   A   {
        abstract   void   a();

        static   {
                E   e   =   new   E();
        }

        C   c   =   new   C();

        public   A()   {
                System.out.println( "hello,this   is   a ");
                a();

        }
}

class   B   extends   A   {
        static   int   b   =   1;

        C   c   =   new   C();

        void   a()   {
                System.out.println(b);
        }

        public   B()   {
                System.out.println( "hello,this   is   b ");
        }

}

class   C   {
        public   C()   {
                System.out.println( "hello,this   is   c ");
        }
}

class   E   {
        public   E()   {
                System.out.println( "static   e ");
        }
}

执行结果:
static   e
hello,this   is   c
hello,this   is   a
1
hello,this   is   c
hello,this   is   b
=============================
hello,this   is   c
hello,this   is   a
1
hello,this   is   c
hello,this   is   b
将标记1处注释掉后,执行结果:
=============================
static   e
hello,this   is   c
hello,this   is   a
1
hello,this   is   c
hello,this   is   b

static只能初始化一次么?

------解决方案--------------------
当你第一次用到A这个类的时候类加载器会加载类A,
之后会对A进行类初始化,包括static域的初始化和static块的初始化
这时候
static {
E e = new E();
}
会被执行.
当第二次在用到类A的时候,虚拟机发现A已经装载了,则不会再去装载它,所以之被执行了一次.

另外~有的程序,A类不再被使用,而变成不可触及状态,其对应的A.class有可能会被垃圾回收器收集.如果被收集了,再需要使用类A的时候还要再装载.