1.初始化规则:
下面规则优先级从前往后依次降低
0.加载一个类时先初始化基类后初始化扩展类;
1.类的初始化高于对象的初始化;
类的初始化依靠静态代码(被static标识的),静态代码块、静态变量这些用于初始化类的成员只会被加载执行一次;
对象的初始化依靠对象成员变量、代码块、构造方法,这些在对象每次被创建时都要执行一次;
2.变量声明执行优先级高于代码块执行,代码块高于构造函数;
3.声明顺序和执行顺序一致;
2.测试性代码
public class DemoTest {
public static void main(String[] args) throws ClassNotFoundException {
DemoBase obj1 = new DemoBaseExtends();
DemoBase obj2 = new DemoBaseExtends();
obj1.toString();
obj2.toString();
}
}
class DemoBase{
static{
System.out.println("DemoBase static called1");
i = 1;
}
{
System.out.println("DemoBase object called1");
}
public DemoBase() {
System.out.println("DemoBase constu called");
}
{
System.out.println("DemoBase object called2");
}
static{
System.out.println("DemoBase static called2");
i = 1;
}
static final String str = "qwer";
static int i;
}
class DemoBaseExtends extends DemoBase{
String name = null;
static{
System.out.println("DemoBaseExtends static called1");
}
{
System.out.println("DemoBaseExtends Object called1");
name = "DemoBaseExtends";
}
public DemoBaseExtends() {
super();
System.out.println("DemoBaseExtends constu called");
}
{
System.out.println("DemoBaseExtends Object called2");
}
static{
System.out.println("DemoBaseExtends static called2");
}
}
/**
DemoBase static called1
DemoBase static called2
DemoBaseExtends static called1
DemoBaseExtends static called2
DemoBase object called1
DemoBase object called2
DemoBase constu called
DemoBaseExtends Object called1
DemoBaseExtends Object called2
DemoBaseExtends constu called
DemoBase object called1
DemoBase object called2
DemoBase constu called
DemoBaseExtends Object called1
DemoBaseExtends Object called2
DemoBaseExtends constu called
*/
3.汇总
基类静态变量(按声明顺序)=》
基类静态代码块(按声明顺序)=》
扩展类静态变量(按声明顺序)=》
扩展类静态代码块(按声明顺序)=》
基类实例变量(按声明顺序)=》
基类实例代码块(按声明顺序)=》
基类构造函数(按调用顺序)=》
扩展类实例变量(按声明顺序)=》
扩展类实例代码块(按声明顺序)=》
扩展类构造函数(按调用顺序)
网友评论