初始化代码块和构造函数的顺序

/*
初始化代码块和构造函数的次序


*/


class Root
{
static
{
System.out.println("Root's static init unit");


}
{
System.out.println("Root's normal init unit");
}


Root()
{
System.out.println("Root's constructor");
}


}




class Mid extends Root
{
static
{
System.out.println("Mid's static init unit");


}
{
System.out.println("Mid's normal init unit");
}
Mid()
{
System.out.println("Mid's constructor:");
}


Mid(String str)
{
this();
System.out.println("Mid's constructor:"+str);
}


}


class Leaf extends Mid
{
static
{
System.out.println("Leaf's static init unit");


}
{
System.out.println("Leaf's normal init unit");
}


Leaf()
{
super("Java");


System.out.println("Leaf's constructor");
}


}


class MainClass
{
public static void main(String[] args)
{
new Leaf();
System.out.println("===============");
new Leaf();


}




}
/*
简单一句话:有父才有子。子类加载必定从最顶级的父类开始加载并类初始化(执行静态代码块,初始化静态成员变量,两者按代码次序执行),子类对象的构造必定从最顶级的父类开始构造并初始化。


次序:父类加载到内存并执行静态代码块-->子类加载到内存并执行静态代码块
父类构造代码块-->父类构造函数-->子类构造代码块-->子类构造函数,其中父类构造函数的选择是由子类指定的。
类一旦加载到了内存,就不会再次加载并初始化了。
静态修饰的成员(成员变量和成员函数)都属于类,可以用类名.调用;非静态的成员(成员变量和成员函数)都属于对象,用对象.调用。
尽量避免用对象调用静态成员。

*/


</pre><pre code_snippet_id="359336" snippet_file_name="blog_20140523_1_4117598" name="code" class="java"><span style="font-family:Arial, Helvetica, sans-serif;"><span style="white-space: normal;">
</span></span>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值