|
|
|
|||
|
Providing Constructors for Your ClassesAll 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 theStack 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:
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:
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: Similarly, when you write the following code, the compiler chooses the default constructor:new Stack(10); 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.new Stack();
The constructor for the following subclass of
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:
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:
| |||
|