Java Reference
In-Depth Information
String title;
String[] authors;
int yearReleased, nrOfPages;
int copiesSold = 0;
public static void main(String[] args) {
final Book superLargeBook = new Book();
superLargeBook.title = "Super Large Boring Book";
superLargeBook.nrOfPages = 1400;
// Change the amount of copies sold
superLargeBook.copiesSold += 1000;
}
}
Note how superLargeBook is final. However, later on, you have to modify the number of copies
sold for this object. How is this possible when the code declared this object as final? After all, you
should not be able to change it, right? The reasoning here is that final affects the number of times a
variable may be initialized, or set. It does not mean that all the fields of an object (when the variable
represents an object) will become “frozen” as well.
To illustrate the difference, the following code shows what you cannot do:
class Book {
final static int MAX_AMOUNT_OF_PAGES = 500;
final static int MIN_AMOUNT_OF_PAGES = 50;
String title;
String[] authors;
int yearReleased, nrOfPages;
int copiesSold = 0;
public static void main(String[] args) {
final Book superLargeBook = new Book();
superLargeBook.title = "Super Large Boring Book";
superLargeBook.nrOfPages = 1400;
// Change the amount of copies sold
superLargeBook.copiesSold += 1000;
// Assign a new book
superLargeBook = new Book(); // EEK!
}
}
Eclipse throws an error, telling you that you are not allowed to assign a new book (or any other
existing book) to the superLargeBook variable.
The same reasoning holds for composite types (arrays). The following code again shows an example:
final int[] numbers = new int[]{1,2,3};
Search WWH ::




Custom Search