Previous | Next | Trail Map | Learning the Java Language | Objects and Classes in Java


Providing Constructors for Your Classes

All Java classes have constructors that are used to initialize a new object of that type. A constructor has the same name as the class. For example, the name of the Stack class's constructor is Stack, the name of the Rectangle class's constructor is Rectangle, and the name of the Thread class's constructor is Thread. Stack defines a single constructor:
public Stack() {
    items = new Vector(10);
}
Java supports name overloading for constructors so that a class can have any number of constructors, all of which have the same name. Following is another constructor that could be defined by Stack. This particular constructor sets the initial size of the stack according to its parameter:
public Stack(int initialSize) {
    items = new Vector(initialSize);
}
Both constructors share the same name, Stack, but they have different parameter lists. The compiler differentiates these constructors based on the number of parameters in the list and their types.

Typically, a constructor uses its arguments to initialize the new object's state. When creating an object, choose the constructor whose arguments best reflect how you want to initialize the new object.

Based on the number and type of the arguments that you pass into the constructor, the compiler can determine which constructor to use. The compiler knows that when you write the following code, it should use the constructor that requires a single integer argument:

new Stack(10);
Similarly, when you write the following code, the compiler chooses the default constructor:
new Stack();
When writing your own class, you don't have to provide constructors for it. The default constructor is automatically provided by the runtime system for any class that contains no constructors. The default provided by the runtime system doesn't do anything. So, if you want to perform some initialization, you will have to write some constructors for your class.

The constructor for the following subclass of Thread performs animation, sets up some default values, such as the frame speed and the number of images, and then loads the images:

class AnimationThread extends Thread {
    int framesPerSecond;
    int numImages;
    Image[] images;

    AnimationThread(int fps, int num) {

        super("AnimationThread");
        this.framesPerSecond = fps;
        this.numImages = num;

        this.images = new Image[numImages];
        for (int i = 0; i <= numImages; i++) {
            . . .
            // Load all the images.
            . . .
        }
    }  
                              . . .
}
Note how the body of a constructor is like the body of a method; that is, it contains local variable declarations, loops, and other statements. However, one line in the AnimationThread constructor that you wouldn't see in a method is the second line:
super("AnimationThread");
This line invokes a constructor provided by the superclass of AnimationThread, namely, Thread. This particular Thread constructor takes a String that sets the name of Thread. Often a constructor wants to take advantage of initialization code written in a class's superclass. Indeed, some classes must call their superclass constructor in order for the object to work properly. If present, the superclass constructor must be the first statement in the subclass's constructor: An object should perform the higher-level initialization first.

When declaring constructors for your class, use the following access specifiers in the constructor declaration to specify what other objects can create instances of your class:

private
No other class can instantiate your class. Your class may contain public class methods (sometimes called factory methods), and those methods can construct an object and return it, but no other classes can.
protected
Only subclasses of your class can create instances of it.
public
Any class can create an instance of your class.
package
Only classes within the same package as your class can construct an instance of it.
Constructors provide a way to initialize a new object. Initializing Instance and Class Members describes other ways you can provide for the initialization of your class and a new object created from the class. That section also discusses when and why you would use each technique.


Previous | Next | Trail Map | Learning the Java Language | Objects and Classes in Java