Java Reference
In-Depth Information
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"));
}
}
Solution 51: What's the Point?
The
main
method creates and prints a
ColorPoint
instance. The
println
method invokes the
toString
method of the
ColorPoint
instance, which is defined in
Point
. The
toString
method
simply returns the value of the
name
field, which is initialized in the
Point
constructor by calling
the
makeName
method. For a
Point
instance, the
makeName
method returns a string of the form
[x,y]
. For a
ColorPoint
instance,
makeName
is overridden to return a string of the form
[x,y]:color
. In this case, x is 4, y is 2, and the color is purple, so the program prints
[4,2]:purple
, right? No. If you ran the program, you found that it prints
[4,2]:null
. What is the
matter with the program?
The program suffers from a problem with the order of instance initialization. To understand the
problem, we will trace the program execution in detail. Here is an annotated program listing to
guide us:
class Point {
Search WWH ::
Custom Search