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只能初始化一次么?
我创建B或者A的多个对象,static都只被执行一次那static域可以有些怎样的具体应用呢。
之后会对A进行类初始化,包括static域的初始化和static块的初始化
这时候
static {
E e = new E();
}
会被执行.
当第二次在用到类A的时候,虚拟机发现A已经装载了,则不会再去装载它,所以之被执行了一次.另外~有的程序,A类不再被使用,而变成不可触及状态,其对应的A.class有可能会被垃圾回收器收集.如果被收集了,再需要使用类A的时候还要再装载.