Java Reference
In-Depth Information
any longer, unless you also explicitly define it. Meaning that for this example, you can no longer
write:
Book myBook = new Book("Title of the Book"); // This works
Book myBook = new Book(); // This no longer works
You might be confused by the wording of “unless you also explicitly define it.” Is it possible
to define multiple constructor methods? Indeed it is; consider, for example, the following class
definition:
class Book {
final static int DEFAULT_YEAR = 2014;
final String title;
final int releaseYear;
int copiesSold;
Book(String t) {
title = t;
releaseYear = DEFAULT_YEAR;
// copiesSold will default to 0
}
Book(String t, int r) {
title = t;
releaseYear = r;
// copiesSold will default to 0
}
Book(String t, int r, int s) {
title = t;
releaseYear = r;
copiesSold = s;
}
}
Given everything you've seen so far, you should be able to understand this class. Take some time to
figure out what is happening here, and make sure to note the following:
Three constructors are available for this class, each taking a different number of arguments.
One final static variable is acting as a constant that will be used as a default initializing value
in one of the constructors.
The two other blank final variables (non‐static) need to be initialized by every constructor.
Constructors can also initialize nonfinal variables.
Note Using methods with the same name—but taking different arguments—
is provided by a feature called method overriding. As the name suggests, this
feature is not only available for constructors, but in fact for every method.
Method overriding provides advanced capabilities, so it's covered in‐depth in
Chapter 8.
Search WWH ::




Custom Search