1

有人可以解释一下为什么如果我运行这段代码输出是 [4, 2]:null 而不是 [4,2]: Purple?我的理解是问题出在超类中的 toString 方法中。实际上,如果我从 SuperClass 中的 toString 中删除“final”并编写一个 toString 方法,例如

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

3 回答 3

3

当你这样做:

super(x, y);

它调用你的超类的构造函数,因此调用makeName()方法(由于 line 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;
    }
}
于 2013-11-24T12:42:57.530 回答
0

您的 toString() 方法返回 variable 的值name。这个变量是在你的超类的构造函数中通过调用被覆盖的方法来填充的makeName()

此时color子类的变量还没有被填充,所以正确返回[4,2]:null

于 2013-11-24T12:43:51.087 回答
0

在将值分配给 color 之前调用 super(int, int),因此在 color 有值之前调用 makeName(),因此:null。

于 2013-11-24T12:44:20.553 回答