原文链接:http://blog.sina.com.cn/s/blog_6caeccff0100q5wz.html
类初始化时构造函数调用顺序:
(1)初始化对象的存储空间为零或null值;
(2)调用父类构造函数;
(3)按顺序分别调用类成员变量和实例成员变量的初始化表达式;
(4)调用本身构造函数。
例子:
public class Dollar extends Money{
Rmb r=new Rmb();
public Dollar(){
System.out.println("Dollar is construct!");
}
public static void main(String[] args){
new Dollar();
}
}
class Money{
public Money(){
System.out.println("Money isconstruct");
}
}
class Rmb{
public Rmb(){
System.out.println("RMB isconstruct");
}
}
输出结果:
Money is construct
RMB is construct
Dollar is construct!
public class Dog {
public Dog() {
System.out.println("Dog");
}
static{ //静态块
System.out.println("super static block");
}
{
System.out.println("super block");
}
}
public class Mastiff extends Dog {
public Mastiff() {
System.out.println("Mastiff");
}
{
System.out.println("block");
}
static {
System.out.println("static block");
}
public static void main(String[] args){
Mastiff mastiff=new Mastiff(); //实例化一个对象
}
}
输出结果:super staticblock staticblock superblock Dog block Mastiff |
也就是说此时的运行顺序为: