class Point{
protected final int x,y;
private final String name;
Point(int x,int y){
this.x = x;
this.y = y;
name = makeName();
}
protected String makeName(){
return "[" + x + "," + y + "]";
}
public final String toString(){
return name;
}
}
public class JieHuo extends Point{
private final String color;
JieHuo(int x,int y,String color){
super(x,y);
this.color = color;
}
protected String makeName(){
return super.makeName() + ":" + color;
}
public static void main(String[] args){
System.out.println(new JieHuo(4,2,"purple"));
}
}
实际输出:[4,2]:null
所以color就是NULL。
System.out.println(new JieHuo(4,2,"purple"));
先执行父类构造方法
Point(int x,int y){
this.x = x;
this.y = y;
name = makeName();
}
之后x=4,y=2
执行 name = makeName();这行代码的时候执行的是子类重写的makeName方法
此时子类构造器没有执行,所以
protected String makeName(){
return super.makeName() + ":" + color;
}
中的color为空
所以打印[4,2]:null
也就是执行 name = makeName();语句时候,JVM调用的是子类重写的makeName方法,而不是父类本身具有的makeName方法。 关于动态绑定问题可以看看我的博客《java动态绑定机制实现多态》(2) 初始化顺序问题,子类初始化完毕之前一定要完成父类初始化。换句话说,老爸都没出生,儿子从哪来?
this.color = color;
也就是说这条语句没有执行,而super()又必须放在最前面,那有没有办法让程序执行上面那条语句呢?!!!!