Java Reference
In-Depth Information
Note The previous testing code snippets can also be placed in the main
method of Book , but remember that it is generally not a good idea to “pollute”
classes representing real‐world concepts with main methods. Alternatively,
you may also create a MyProgram class and put the code snippets in its main
method, similar to what you did in the course administration example earlier in
this chapter.
However, Eclipse will refuse to compile this code, as it complains that you cannot give the title
variable a new value (“Super Large Boring Book”), as it has already received its value at the time
of creating the object (“Unknown Title”). To get this code to work, you might be inclined to make
title a blank final variable, like so:
class Book {
final String title;
final String[] authors;
final 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;
}
}
Note that I have also reworked some other variables, as it makes sense that the title, authors, num-
ber of pages, and the release date never change for a book (not taking into account reprints and
other such intricacies at the moment). Hence, it makes sense to set these to read‐only.
However, you will notice that Java will still complain about the title and nrOfPages assignments
and refuse to compile this code fragment. Why? Especially when the following code (you can put
this somewhere in the main method) does in fact work:
final int a;
a = 5;
The reason lies in the fact that title , authors , yearReleased , and so on are class variables,
whereas the a integer is just a local variable. Remember that when you initialize an object, Java will
assign default values to the instance and class variables for which no value was set. For final vari-
ables, on the other hand, Java will not set an initial value and will force you, the programmer, to
explicitly provide an initial value. For local variables inside our main method, we can define a blank
variable and initialize it later (before using it), as seen above, but for instance and class variables,
this remark entails that we cannot do the following:
class Book {
final String title;
}
Search WWH ::




Custom Search