2013-11-24 77 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。