Default and Parameterless Constructors
Every class must have at least one constructor. Recall from Section 4.9 that if you do not provide any constructors in a class's declaration, the compiler creates a default constructor that takes no arguments when it is invoked. In Section 10.4.1, you will learn that the default constructor implicitly performs a special task.
The compiler will not create a default constructor for a class that explicitly declares at least one constructor. In this case, if you want to be able to invoke the constructor with no arguments, you must declare a parameterless constructoras in line 11 of Fig. 9.7. Like a default constructor, a parameterless constructor is invoked with empty parentheses. Note that the Time2 parameterless constructor explicitly initializes a Time2 object by passing to the three-parameter constructor 0 for each parameter. Since 0 is the default value for int instance variables, the parameterless constructor in this example could actually omit the constructor initializer. In this case, each instance variable would receive its default value when the object is created. If we omit the parameterless constructor, clients of this class would not be able to create a Time2 object with the expression new Time2().
|
Composition
|