2013-11-24 57 views
1

有人可以请解释我为什么如果我运行此代码的输出是[4,2]:null,而不是[4,2]:紫色? 我的理解是,问题出现在superClass的toString方法中。 事实上,如果从我的toString在子类中删除“最后”的超类,并且编写一个toString方法类似Java超级方法调用子类型重写方法

public String toString() { 
     return this.makeName(); 
    } 

一切工作正常。 但我不太了解背后的概念。 是否存在某些关于此的内容?

谢谢你的时间。

public class Point { 
    protected final int x, y; 
    private final String name; 

    public 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; 
    } 
} 

ColorPoint.java:

public class ColorPoint extends Point { 
    private final String color; 

    public ColorPoint(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 ColorPoint(4, 2, "purple")); 
    } 
} 

回答

3

当你这样做:

super(x, y);

它调用你的超类的构造函数,因此makeName()方法(由于线路name = makeName();)。

由于您在您的子类中重新定义了它,因此它会调用它,但此时不定义颜色。

因此return super.makeName() + ":" + color;相当于return super.makeName() + ":" + null;

所以执行流程是在下面(简化的)等效:

new ColorPoint(4, 2, "purple") //<-- creating ColorPoint object 
super(x, y); //<-- super call 
this.x = 4; 
this.y = 2; 
name = makeName(); //<-- call makeName() in your ColorPoint class 
return super.makeName() + ":" + color; //<-- here color isn't defined yet so it's null 
name = "[4, 2]:null"; 
color = "purple"; 
/***/ 
print [4, 2]:null in the console //you call the toString() method, since it returns name you get the following output 


注意,你真的可以用下面的简化你的类:

class Point { 
    protected final int x, y; 

    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    @Override 
    public String toString() { 
     return "["+x+", "+y+"]"; 
    } 
} 

class ColorPoint extends Point { 
    private final String color; 

    public ColorPoint(int x,int y, String color) { 
     super(x, y); 
     this.color = color; 
    } 

    @Override 
    public String toString() { 
     return super.toString() + ":" + color; 
    } 
} 
0

您的toString()方法返回变量0123的值。该变量在超类的构造函数中被填充,方法是调用覆盖的方法makeName()

这时,子类的可变color尚未填补,所以正确返回[4,2]:null

0

您指定的值颜色之前调用超(INT,INT),所以makeName()是在颜色具有值之前调用,因此:null。