对象的初始化过程

下面代码的运行顺序:

先super(),父类中进行构造函数,调用show,子类方法将父类中的show覆盖,super运行完成,显示初始化,再进行子类构造函数的运行

package com.monfolld;
class Fu{
    Fu(){                                           //2
        show();                                     
    }
    void show(){
        System.out.println("hehe");
    }
}
class Zi extends Fu{
    int num=9;
    Zi(){
        super();                                     //1
        //显示初始化,在父类构造函数之后                //3
        System.out.println("zi constructor"+num);    //4
    }
    void show(){
        System.out.println("show.."+num);
    }
}
class Test {
    public static void main(String[] args){
    new Zi();
    }
}

 当有构造代码块时,new一个对象,先进行构造函数加载,第一步对象初始化,第二步构造器,第三步父类的加载,第四步显示初始化,第五步,构造代码块,第六步构造函数具体数初始化。

package com.monfolld;
class Fu{                                                  //3
    Fu(){
        System.out.println("fu contructor run");
        show();
    }
    void show(){
        System.out.println("hehe");
    }
}
class Zi extends Fu{
    int num=9;
    {
        System.out.println("constructor code..."+num);
        num=10;
    }
    Zi(){                                                    //1
        super();                                             //2
        //显示初始化                                          //4
        //构造代码块初始化                                    //5
        System.out.println("zi constructor"+num);           //6
    }
    void show(){                                             
        System.out.println("show.."+num);
    }
}
class Test {
    public static void main(String[] args){
    new Zi();
    }
}

当父类中也含有构造代码块时

package com.monfolld;
class Fu{
    int num=9;
    {
        System.out.println("Fu");                //1
    }
    Fu(){
        super();           //Object
        //显示初始化
        //构造代码块初始化
        show();
    }
    void show(){
        System.out.println("hehe");
    }
}
class Zi extends Fu{
    int num=9;
    {
        System.out.println("zi"+num);               //3
        num=10;
    }
    Zi(){
        super();
        //显示初始化,在父类构造函数之后
        //构造代码块初始化
        System.out.println("zi show"+num);
    }
    void show(){
        System.out.println("zi show.."+num);               //2
    }
}
class Test {
    public static void main(String[] args){
    new Zi();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值