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 bstatic只能初始化一次么?

解决方案 »

  1.   

    好像还不是很理解
    我创建B或者A的多个对象,static都只被执行一次那static域可以有些怎样的具体应用呢。
      

  2.   

    当你第一次用到A这个类的时候类加载器会加载类A,
    之后会对A进行类初始化,包括static域的初始化和static块的初始化
    这时候
     static {
            E e = new E();
        }
    会被执行.
    当第二次在用到类A的时候,虚拟机发现A已经装载了,则不会再去装载它,所以之被执行了一次.另外~有的程序,A类不再被使用,而变成不可触及状态,其对应的A.class有可能会被垃圾回收器收集.如果被收集了,再需要使用类A的时候还要再装载.
      

  3.   

    你用hibernate创建SessionFactory的时候,用static只创建一次,一个SessionFactory对应一个数据库,重量级的,不管你怎么弄,一个应用对应一个sessionFactory。