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().

Common Programming Error 9 5

If a class has constructors, but none of the public constructors are parameterless constructors, and an application attempts to call a parameterless constructor to initialize an object of the class, a compilation error occurs. A constructor can be called with no arguments only if the class does not have any constructors (in which case the default constructor is called) or if the class has a public parameterless constructor.

Common Programming Error 9 6

Only constructors can have the same name as the class. Declaring a method, property or field with the same name as the class is a compilation error.

Composition

Категории