Java Reference
In-Depth Information
The general syntax for constructors is the following:
public <class name>(<type> <name>, ..., <type> <name>) {
<statement>;
<statement>;
...
<statement>;
}
When a class doesn't have a constructor, as in our previous versions of the Point
class, Java automatically supplies a default constructor with no parameters. That is
why it was previously legal to construct a new Point() . (The default constructor
auto-initializes all fields to zero-equivalent values.) However, Java doesn't supply the
default empty constructor when we supply a constructor of our own, so it is illegal to
construct Point objects without passing in the initial x and y parameters:
Point p1 = new Point(); // will not compile for this version
In the next sections, we'll write additional code to restore this ability.
Common Programming Error
Using void with a Constructor
Many new programmers accidentally include the keyword void in the header of
a constructor, since they've gotten used to writing a return type for every method:
// this code has a bug
public void Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
This is actually a very tricky and annoying bug. Constructors aren't supposed
to have return types. When you write a return type such as void , what you've
created is not a constructor, but rather a normal instance method called Point
that accepts x and y parameters and has a void return type. This error is tough to
catch, because the Point.java file still compiles successfully.
You will see an error when you try to call the constructor that you thought you
just wrote, though, because it isn't actually a constructor. The client code that
Continued on next page
 
Search WWH ::




Custom Search