APPENDIX A: Introduction to Java 387
Constructors
When an object is created using a new operator, the constructors are called to set the initial state
of an object. A constructor declaration is comprised of the accessibility modifier followed by the
parameter list with the following declarations:
Modifiers other than an accessibility modifier are not permitted in the
constructor header.
Constructors cannot return a value and, therefore, do not specify a return type,
not even void, in the constructor header.
The constructor name must be the same as the class name.
When no constructors are specified in a class, then an implicit default constructor, that is, an
implicit constructor without any parameters, is generated for the class by the compiler that
comprises a call to the superclass’s constructor. The compiler inserts this call to a superclass’s
constructor to ensure that the inherited state of the object is initialized. Listing A-10 illustrates a call
to an implicit default constructor.
Listing A-10. Implicit Default Constructor
class ClassA {
int i;
}
class ClassB {
ClassA var1 = new ClassA(); // (1) Call to implicit default constructor.
}
In the listing, the following implicit default constructor is called when a ClassA object is created
in ClassB:
ClassA() { super(); }
In Listing A-11, the class ClassA provides an explicit default constructor at line 4.
Listing A-11. Explicit Default Constructor
- class ClassA {
- int i ;
- // Explicit Default Constructor:
- ClassA() {
- i = 1;
- }
- }
- class ClassB {
- // ...
- ClassA var1 = new ClassA(); // Call of explicit default constructor.
- }