Java Reference
In-Depth Information
Book objects with an initial title that's kept as a read‐only variable (using final ). You might also
recall that when you do the following:
Book myBook = new Book();
You are writing () as if you are invoking a method, because, in fact, you are—namely the construc-
tor method for the class. Constructor methods are defined similarly as instance methods, with the
following differences:
Constructors bear the same name as the class in which they are defined.
Constructors have no return type, not even void .
In all the classes you have seen so far, you will notice that you did not define a constructor method.
The reason for this is that Java will automatically assume a “blank” constructor when you do not
define one, meaning that defining a class like:
Class Book {
}
Is exactly the same as writing:
class Book {
Book() {
}
}
So far, this constructor does not really do much. What can they be used for? A constructor is
invoked each time you instantiate (that is, “construct”) a new object using the new keyword.
Most commonly, constructors will initialize default values for the object being created. To illus-
trate this, let's return to the earlier issue: you aim to define a variable to hold the title of a book,
but you want to define this variable so it can be set only once. As such, the following solution
does not suffice:
class Book {
String title;
}
As there is nothing preventing multiple assignments to title in this case. You have seen that you can
use the final keyword like so:
class Book {
final String title = "Initial Title";
}
But of course, you would like to make the initial title user‐specified and different for each book. The
previous solution does not allow you to write:
Book myBook = new Book();
myBook.title = "The Real Title";
Search WWH ::




Custom Search