标签:style color ar java strong sp on new size
类初始化时构造函数调用顺序:
(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 is construct");
}
}
class Rmb{
public Rmb(){
System.out.println("RMB is construct");
}
}
输出结果:
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 static block static block super block Dog block Mastiff |
也就是说此时的运行顺序为:
标签:style color ar java strong sp on new size
原文地址:http://www.cnblogs.com/lukec8650/p/4015450.html