构造器调用顺序说明
- 调用基类(父类)构造器,这个步骤不断反复递归下去,首先是构造这种层次的根,然后是下一个导出类(子类),直到最底层导出类
- 按声明顺序调用成员的初始化方法
- 调用导出类构造器的主体(当前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()
构造器内部的多态方法的行为
初始化的实际过程:
- 在其他任何事物发生之前,将分配给对象的存储空间初始化成二进制的零
- 如前所述那样调用基类构造器。此时,调用被覆盖的draw()方法(要在调用RoundGlyph构造器之前调用),由于步骤一的缘故,此时radius的值为0
- 按照声明的顺序调用成员的初始化方法
- 调用导出类的构造器主体
代码示例
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编程思想
如有错误,欢迎指正!