Java Reference
In-Depth Information
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
1. class ClassA {
2. int i;
3. // Only non-default Constructor:
4. ClassA(int i) {
5. this.i = i;
6. }
7. }
8. class ClassB {
9. // ...
10. ClassA var1 = new ClassA(2);
11. //ClassA var2 = new ClassA(); // Compile-time error.
12. }
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
1. class ClassA {
2. int i;
3. // Explicit Default Constructor:
4. ClassA() {
5. i = 3;
6. }
7. // Non-default Constructor:
8. ClassA(int i) {
9. this.i = i;
10. }
11. }
12. class ClassB {
13. // ...
14. ClassA var1 = new ClassA(4);
15. ClassA var2 = new ClassA();
16. }
Search WWH ::




Custom Search