388 APPENDIX A: Introduction to Java
The explicit default constructor ensures that any object created with the object creation expression
new ClassA( ), shown in ClassB, will have its field i initialized to 1. If a class defines any explicit
constructors, then the compiler will not generate the implicit default constructor with a call to the
superclass’s constructor, and therefore the state of the object will not be set. In such a case, an
implementation of the default constructor needs to be provided. In Listing A-12, the class ClassA
provides only a nondefault constructor at line 4. It is called at line 8 when an object of the class
ClassA is created with the new operator. Any attempt to call the default constructor will be flagged as
a compile-time error, as shown on line 11.
Listing A-12. Nondefault Constructor
- class ClassA {
- int i;
- // Only non-default Constructor:
- ClassA(int i) {
- this.i = i;
- }
- }
- class ClassB {
- // ...
- ClassA var1 = new ClassA(2);
- //ClassA var2 = new ClassA(); // Compile-time error.
- }
Constructors can be overloaded, like methods, and because the names of all the constructors are
restricted to be the same as the class’s name, the signatures of these constructors can be different
only if their parameter lists are different. In Listing A-13, the class ClassA provides both an explicit
implementation of the default constructor on line 4 and a nondefault constructor on line 8. The
nondefault constructor is called when an object of the class ClassA is created on line 14 and the
default constructor is called on line 15.
Listing A-13. Both Default and Nondefault Constructor
- class ClassA {
- int i;
- // Explicit Default Constructor:
- ClassA() {
- i = 3;
- }
- // Non-default Constructor:
- ClassA(int i) {
- this.i = i;
- }
- }
- class ClassB {
- // ...
- ClassA var1 = new ClassA(4);
- ClassA var2 = new ClassA();
- }