Overloaded Constructors
Like methods, constructors can be overloaded. Since the constructors in a class all have the same name as the class, their signatures are differentiated by their parameter lists. In the following example, the class Light now provides explicit implementation of the no-argument constructor at (1) and that of a non-zero argument constructor at (2). The constructors are overloaded, as is evident by their signatures. The non-zero argument constructor at (2) is called when an object of the class Light is created at (4), and the no-argument constructor is likewise called at (3). Overloading of constructors allows appropriate initialization of objects on creation, depending on the constructor invoked (see chaining of constructors in §5.3, p. 209). It is recommended to use the @param tag in a Javadoc comment to document the formal parameters of a constructor.
class Light {
// …
// No-argument constructor:
Light() { // (1)
noOfWatts = 50;
indicator = true;
location = “X”;
}
// Non-zero argument constructor:
Light(int noOfWatts, boolean indicator, String location) { // (2)
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
}
//…
}
class Greenhouse {
// …
Light firstLight = new Light(); // (3) OK. Calls (1)
Light moreLight = new Light(100, true, “Greenhouse”); // (4) OK. Calls (2)
}
3.8 Static Member Declarations
In this section we look at static members in classes, but in general, the keyword static is used in the following contexts:
- Declaring static fields in classes (p. 113), enum types (§5.13, p. 290) and interfaces (§5.6, p. 254)
- Declaring static methods in classes (p. 115), enum types (§5.13, p. 290) and interfaces (§5.6, p. 251)
- Declaring static initializer blocks in classes (§10.7, p. 545) and enum types (§5.13, p. 290)
- Declaring nested static member types (§9.2, p. 495)