1)如果有父类,先初始化父类
2)类只被初始化一次,即类中的静态变量及静态代码块只在第一次加载时执行一次
3)类第一次初始化时先初始化静态变量,执行静态代码块
4)执行完静态代码后先初始化成员变量,然后执行构造器。
例:
输出:
say hello!
shap static draw construction
circle static draw construction
shap draw construction
shap construction
circle draw construction
circle construction
2)类只被初始化一次,即类中的静态变量及静态代码块只在第一次加载时执行一次
3)类第一次初始化时先初始化静态变量,执行静态代码块
4)执行完静态代码后先初始化成员变量,然后执行构造器。
例:
package com.zsoft.test;
public class ClassLoadTest {
public static void main(String[] args){
new Circle();
}
}
class Draw{
public static String hello = "say hello!";
static{
System.out.println(hello);
}
public Draw(){
System.out.println("draw construction");
}
public Draw(String type) {
System.out.println(type + " draw construction");
}
}
class Shape{
public static Draw drawStatic = new Draw("shap static");
private Draw draw = new Draw("shap");
public Shape(){
System.out.println("shap construction");
}
}
class Circle extends Shape {
private Draw draw = new Draw("circle");
public static Draw drawStatic = new Draw("circle static");
public Circle(){
System.out.println("circle construction");
}
}
输出:
say hello!
shap static draw construction
circle static draw construction
shap draw construction
shap construction
circle draw construction
circle construction