- 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"));
- }
- }
复制代码 上面这段程序main 方法创建并打印了一个ColorPoint 实例。
println 方法调用了该ColorPoint 实例的toString 方法,这个方法是在Point 中定义的;
toString方法将直接返回name 域的值,这个值是通过调用makeName 方法在Point 的构造器中被初始化的;
makeName 方法被覆写为返回[x,y]:color 形式的字符串。
程序运行结果是[4,2]:null,为什么不是[4,2]:purple? |