Java Reference
In-Depth Information
Continued from previous page
tries to construct the Point object will indicate that it can't find an (int, int)
constructor for a Point :
PointMain.java:7: cannot find symbol
symbol : constructor Point(int, int)
location: class Point
Point p1 = new Point(7, 2);
If you see “cannot find symbol” constructor errors and you were positive that you
wrote a constructor, double-check its header to make sure there's no return type.
Common Programming Error
Redeclaring Fields in a Constructor
Another common bug associated with constructors occurs when you mistakenly
redeclare fields by writing their types. Here's an example that shows this mistake:
// this constructor code has a bug
public Point(int initialX, int initialY) {
int x = initialX;
int y = initialY;
}
The preceding code behaves in an odd way. It compiles successfully, but when
the client code constructs a Point object its initial coordinates are always (0, 0),
regardless of the parameter values that are passed to the constructor:
// this client code will print that p1 is (0, 0)
Point p1 = new Point(7, 2);
System.out.println("p1 is " + p1);
The problem is that rather than storing initialX and initialY in the Point
object's x and y fields, we've actually declared local variables called x and y
inside the Point constructor. We store initialX and initialY in those local
variables, which are thrown away when the constructor finishes running. No val-
ues are ever assigned to the x and y fields in the constructor, so they are automat-
ically initialized to 0 . We say that these local x and y variables shadow our x and
y fields because they obscure the fields we intended to set.
If you observe that your constructor doesn't seem to be setting your object's
fields, check closely to make sure that you didn't accidentally declare local vari-
ables that shadow your fields. The key thing is not to include a type at the front
of the statement when you assign a value to a field.
 
Search WWH ::




Custom Search