有人可以解释一下为什么如果我运行这段代码输出是 [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"));
}
}