java类初始化
内部类在被调用的时候初始化
类初始化顺序如下
1. 初始化父类静态代码块
2. 初始化子类静态代码块
3. 初始化父类变量
4. 初始化子类变量
5. 初始化父类构造
6. 初始化字类构造
public class Sub extends Super{
static {
System.out.println("sub static"); //@2
}
public Sub(){
System.out.println("sub----"); //@5
}
@Override
public void overrideMe() {
System.out.println(date);
}
public static void main(String[]args){
Sub sub=new Sub();
sub.overrideMe();
}
}
public class Super {
static {
System.out.println("super static");//@1
}
protected static Date date=new Date();//@3
public Super(){
System.out.println("super========");//@4
overrideMe();}
public void overrideMe(){}
}
/*执行顺序
super static
sub static
super========
Sun Jul 31 11:35:53 CST 2016
sub----
Sun Jul 31 11:35:53 CST 2016
*/
如果父类同时有两个构造方法,在子类构造方法中未调用父类构造函数,默认使用父类无参数构造。
public class Sub extends Super{
static {
System.out.println("sub static");
}
public Sub(){
super(3);
System.out.println("sub=====");
}
@Override
public void overrideMe() {
System.out.println(date);
}
public static void main(String[]args){
Sub sub=new Sub();
sub.overrideMe();
}
}
public class Super {
static {
System.out.println("super static");
}
protected static Date date=new Date();
public Super(){
System.out.println("super========");
}
public Super(int i){
System.out.println("super -"+i+" -========");
overrideMe();}
public void overrideMe(){}
}
/*
super static
sub static
super -3 -========
Disconnected from the target VM, address: '127.0.0.1:52336', transport: 'socket'
Sun Jul 31 11:48:32 CST 2016
sub=====
Sun Jul 31 11:48:32 CST 2016
*/