返回顶部

收藏

java复杂对象调用构造器顺序

更多
/**
 *
 * Created on 15-12-21.
 */
class Meal {
    Meal() {
        System.out.println("Meal()");
    }
}

class Bread {
    Bread() {
        System.out.println("Bread()s");
    }
}

class Cheese {
    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");
    }
}

public class Sandwich extends PortableLunch {
    private Bread b = new Bread();
    private Cheese c = new Cheese();
    private Lettuce l = new Lettuce();
    public static void main(String[] args) {
        new Sandwich();
    }
}

/**
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
*/

首先调用基类构造器,反复递归,直到到达根,然后在下一层导出类,直到最底层导出类 其次 按照声明顺序调用成员的初始化方法 再次 调用导出类的构造方法

标签:

收藏

0人收藏

支持

0

反对

0

发表评论