Java Reference
In-Depth Information
If we try to do this, Java will warn that we have not initialized the little variable.
Given this point, it might occur to you that final class variables are, for now, pretty useless. You
have found no way to create topics with a given initial title that's kept as a read‐only variable. To
resolve this, you need to understand another concept: object constructors . Don't worry, you will
learn about these a few pages later, and you will revisit final class variables there as well.
There is, however, another way that final variables come in handy, and that is when you use them in
combination with static variables. Change the Book class again to look like the following:
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) {
Book superLargeBook = new Book();
superLargeBook.title = "Super Large Boring Book";
superLargeBook.nrOfPages = 1400;
System.out.println("Check if your book has a correct amount of pages...");
System.out.println("- Minimum amount: "+Book.MIN_AMOUNT_OF_PAGES);
System.out.println("- Maximum amount: "+Book.MAX_AMOUNT_OF_PAGES);
System.out.println("- Your book: "+superLargeBook.nrOfPages);
}
}
Note the two final static variables at the top of the class body. This pattern is very heavily used
by Java programmers to define constants, meaning that you desire to set the maximum and mini-
mum amount of pages only once (they are final), and also to keep them shared by all objects (they
are part of the class blueprint). Note by the way that Java has a const keyword, but it currently
remains unused.
Also observe the change in naming convention when declaring constants with final static vari-
ables. Instead of writing in lowerCamelCase , you name them using CAPITALIZED_UNDERSCORE_
SEPARATED form. Again, this is not required, but it's a widely followed convention by Java
programmers to indicate constant variables.
There is one final (no pun intended) important remark I need to make regarding final variables.
Remember that I have stated that final variables can only be initialized once, and then keep their
value. For primitive types, the effects of this are easy to grasp—a final integer set to the number
five remains five for the remainder of its life. However, for more complex types, such as objects, the
story is a little more complicated. Consider the following example:
class Book {
final static int MAX_AMOUNT_OF_PAGES = 500;
final static int MIN_AMOUNT_OF_PAGES = 50;
Search WWH ::




Custom Search