class Point {
protected final int x, y;
private final String name; // Cached at construction time
Point(int x, int y) {
this.x = x;
this.y = y;
name = makeName();
}
protected String makeName() {
return "[" + x + "," + y + "]";
}
public final String toString() {
/*
if (name == null)
name = makeName();
*/
return name;
}
}
public class ConstructIni extends Point {
private final String color;
ConstructIni(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 ConstructIni(4, 2, "purple"));
}
}
这里在color还没有来得及被赋值的时候,已经通过被override的makeName调用了,取得null值。
最终结果是:[4,2]:null
此时应当改写:红色部分注释去掉,没有注释的要删除。这个叫做Lazy initialization