Java Reference
In-Depth Information
Finally, you have seen that you can remove the initialization of the variable to make it a so‐called
blank final variable:
class Book {
final String title;
}
Recall, however, from our discussion regarding final variables that Java will complain about the fact
that the title instance variable might not be initialized, as you need to explicitly assign a value.
You have seen before that you can solve this by doing something like:
class Book {
final String title = "";
}
But again, we have no way to change the title variable to the title we actually want to give to a
particular book. That is, Java will complain about doing something like:
Book myBook = new Book();
myBook.title = "The Real Title";
This happens because we have already initialized the title variable to "" , preventing it from being
changed again. So how do you deal with this problem? Well, by initializing final variables inside
your own constructor, like so:
class Book {
final String title;
Book() {
title = "Initial Title";
}
}
To supply a user‐specific title, you now can just modify the constructor method so that it takes an
argument. Watch out when naming your constructor arguments. Remember that using local or
parameter variables with the same name as instance variables will take precedence. Hence, you
should modify the constructor like so:
class Book {
final String title;
Book(String t) {
title = t;
}
}
Now how do you call this constructor? Easily, by providing an argument when creating an object:
Book myBook = new Book("Title of the Book");
Note that you have seen how Java will assume the presence of a blank constructor taking
no arguments when you do not define one in the class. If you do define a constructor with
arguments—like you've just seen—the constructor taking no arguments will not be available
Search WWH ::




Custom Search