Monday, September 15, 2008

Initializing an Object in Java

As shown in the code for the rectangle class, classes can provide one or more constructors to initialize a new object of that type. You can recognize a class’s constructors because they have the same name as the class and have no return type. Here are the declarations for rectangle’s constructors:
public rectangle(point p)
public rectangle(int w, int h)
public rectangle (point p, int w, int h)
public rectangle()

Each of these constructors lets you provide initial values for different aspects of the rectangle; the origin the width and height, all three, or none. If a class has multiple constructors, they all have the same name but a different number of arguments or different typed arguments. The compiler differentiates the constructors, and knows which one to call, depending on the arguments. So when compiler encounters the following code, it knows to call the constructor that requires two integer arguments (which initializes the width and height of the new rectangle to the values provided by the argument):
rectangle rect = new rectangle(100,200);
The rectangle constructor used below doesn’t take any arguments :
rectangle rect = new rectangle();
A constructor that takes no arguments, such as the one shown, is the default constructor. If a class does not explicitly define any constructors at all, Java automatically provides a non-argument constructor that does nothing. Thus all classes have at least one constructor.

No comments: