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

解决方案 »

  1.   

    想要输出:[4,2]:purple
    实际输出:[4,2]:null
      

  2.   

    private final String color;
    所以color就是NULL。
      

  3.   

    就是初始化的顺序嘛
    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
      

  4.   

    这是因为调用super(x,y)的时候,程序执行的makeName()方法是JieHuo类里面的makeName而并非是Point里的。
      

  5.   

    4楼正解,支持。这段代码涉及到两方面知识:(1) 方法重载情况下,方法的动态绑定问题?
        也就是执行 name = makeName();语句时候,JVM调用的是子类重写的makeName方法,而不是父类本身具有的makeName方法。 关于动态绑定问题可以看看我的博客《java动态绑定机制实现多态》(2) 初始化顺序问题,子类初始化完毕之前一定要完成父类初始化。换句话说,老爸都没出生,儿子从哪来?
      

  6.   


            this.color = color;
    也就是说这条语句没有执行,而super()又必须放在最前面,那有没有办法让程序执行上面那条语句呢?!!!!