下面这个程序有两个不可变的值类(value class),值类即其实例表示值的类。第一个类用整数坐标来表示平面上的一个点,第二个类在此基础上添加了一点颜色。主程序将创建和打印第二个类的一个实例。那么,下面的程序将打印出什么呢? 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() { return name; } }
public class ColorPoint extends Point { private final String color; 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")); } }
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(); // 3. Invoke subclass method }
protected String makeName() { return "[" + x + "," + y + "]"; } public final String toString() { return name; } }
public class ColorPoint extends Point { private final String color; ColorPoint(int x, int y, String color) { super(x, y); // 2. Chain to Point constructor this.color = color; // 5. Initialize blank final-Too late } protected String makeName() { // 4. Executes before subclass constructor body! return super.makeName() + ":" + color; } public static void main(String[] args) { // 1. Invoke subclass constructor System.out.println(new ColorPoint(4, 2, "purple")); } }
class Point { protected final int x, y; private String name; // Lazily initialized Point(int x, int y) { this.x = x; this.y = y; // name initialization removed }
protected String makeName() { return "[" + x + "," + y + "]"; } // Lazily computers and caches name on first use public final synchronized String toString() { if (name == null) name = makeName(); return name; } }