Java基础之构造器调用顺序

构造器调用顺序说明
  1. 调用基类(父类)构造器,这个步骤不断反复递归下去,首先是构造这种层次的根,然后是下一个导出类(子类),直到最底层导出类
  2. 按声明顺序调用成员的初始化方法
  3. 调用导出类构造器的主体(当前main方法所在类构造器)
代码示例
package eight;

import sevenChapter.Chess;

/**
 * 构造器的调用顺序
 * @author SLH 
 * @date 2016-11-13
 * @version 1.0.0
 */
public class Sandwich extends PortableLunch{
    private Bread bread = new Bread();
    private Cheese cheese = new Cheese();
    Sandwich() {
        System.out.println("Sandwich()");
    }
    private Lettuce lettuce = new Lettuce();
    public static void main(String[] args) {
        new Sandwich();
    }
}
class Meal{
    Meal() {
        System.out.println("Meal()");
    }
}
class Bread{
    Bread() {
        System.out.println("Bread()");
    }
}
class CheeseSuper{
    CheeseSuper() {
        System.out.println("CheeseSuper");
    }
}
class Cheese extends CheeseSuper{
    Cheese(){
        System.out.println("Cheese()");
    }
}
class Lettuce{
    Lettuce() {
        System.out.println("Lettuce");
    }
}
class Lunch extends Meal{
    Lunch() {
        System.out.println("Lunch()");
    }
}
class PortableLunch extends Lunch{
    PortableLunch() {
        System.out.println("PortableLunch()");
    }
}
输出结果Console
Meal()
Lunch()
PortableLunch()
Bread()
CheeseSuper
Cheese()
Lettuce
Sandwich()
构造器内部的多态方法的行为

初始化的实际过程:

  1. 在其他任何事物发生之前,将分配给对象的存储空间初始化成二进制的零
  2. 如前所述那样调用基类构造器。此时,调用被覆盖的draw()方法(要在调用RoundGlyph构造器之前调用),由于步骤一的缘故,此时radius的值为0
  3. 按照声明的顺序调用成员的初始化方法
  4. 调用导出类的构造器主体
代码示例
package eight;
/**
 * 类的描述
 * @author SLH 
 * @date 2016-11-14
 * @version 1.0.0
 */
public class PolyConstructors {
    public static void main(String[] args) {
        RoundGlyph roundGlyph = new RoundGlyph("I'm the two");
    }
}
class Glyph{
    void draw(){
        System.out.println("Glyph.draw()");
    }
    public Glyph() {
        System.out.println("Glyph() before draw()");
        draw();
        System.out.println("Glyph() after draw()");
    }
}
class RoundGlyph extends Glyph{
    private int radius = 1;
    private String string = "I'm the One!";
    public RoundGlyph(int r) {
        System.out.println("RoundGlyph.RoundGlyph(),radius = " + radius);
    }
    public RoundGlyph(String s){
        System.out.println("RoundGlyph.RoundGlyph(),string = " + s);
    }
    void draw(){
        //System.out.println("RoundGlyph.draw(),radius = " + radius);
        System.out.println("RoundGlyph.draw(),string = " + string);
    }
}
输出结果
Glyph() before draw()
RoundGlyph.draw(),string = null
Glyph() after draw()
RoundGlyph.RoundGlyph(),string = I'm the two
编码构造器准则:用尽可能简单的方法使对象进入正常状态;如果可以的话,避免调用其它方法。
注:构造器内唯一能够安全调用的那些方法是基类中的final方法(也适用于private方法,它们自动属于final方法)

摘自Java编程思想
如有错误,欢迎指正!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值