Java在它开始运行之前并非被完全加载,其各个部分仅在必需时才加载。
import java.awt.Color;import smallbird.Tools;
public class Parent {
public static final String RG_CODE="025";
public static String CITY_NAME="南京";
public static Color COLOR_RED=new Color(255,0,0);
public static final Object obj=new Child();
static {
System.out.println("static code block."+Tools.getNowDate());
}
public Parent() {
System.out.println("Parent's Constructor."+Tools.getNowDate());
}
public void speak() {
System.out.println("Parent's speak.");
}
}
1、建议将一些常量声明为final static编译期常量。
若仅声明为static,打印Parent.CITY_NAME时会先执行静态代码块,而打印Parent.RG_CODE却不会。
public static final Color COLOR_RED=new Color(255,0,0); 引用类似这些非常数静态域时会执行static代码块,
2、使用.class来获得对类的引用不会初始化
3、先初始化静态属性,再执行静态代码块
System.out.println("test: "+new Parent());
执行结果:
Parent's Constructor.2015-06-29 22:06:55,577
Child's Constructor.
static code block.2015-06-29 22:06:55,578
Parent's Constructor.2015-06-29 22:06:55,578
test: basic.Parent@ae94e92