Java Reference
In-Depth Information
You might be annoyed by the fact that some statements, such as title = t; , are duplicated across
different constructors, while in fact the constructors are forming a hierarchy. Luckily, it is possible
for constructors to call other constructors to perform a piece of the requested initialization, as the
following code snippet shows:
class Book {
final static int DEFAULT_YEAR = 2014;
final String title;
final int releaseYear;
int copiesSold;
Book(String t) {
// Call other constructor:
this(t, DEFAULT_YEAR, 0);
}
Book(String t, int r) {
// Call other constructor:
this(t, r, 0);
}
Book(String t, int r, int s) {
title = t;
releaseYear = r;
copiesSold = s;
}
}
Note the use of the keyword this here. I've briefly mentioned this keyword before when illustrat-
ing how you can use it to refer to the current object ( this.title ), but here it acts as a way to call
another constructor. Again, don't worry if this is still a bit overwhelming, as the this keyword will
be revisited later. In fact, for now, I will avoid defining multiple constructors until you are ready to
move a step further, so that you will not run into the intricacies relating to defining more than one
constructor. So for now, just keep in mind that it is possible to create multiple constructors within a
class.
Note When you think about the concept of constructors—or if you're com-
ing from other programming languages such as C++—you might wonder if the
counterpart of destructors also exists. In Java, it does not, as the JVM itself will
keep an eye out for objects that are no longer accessible and should thus be
removed automatically. Consider for example:
Book myBook = new Book("My first book");
myBook = new Book("My second book");
myBook = null;
What happens with the "My first book" object stored in the myBook vari-
able once you assign the second book (a new object) to this variable? Since
continues
Search WWH ::




Custom Search