Java Reference
In-Depth Information
However, for the last line, when accessing the static variable, Eclipse complains about the fact that
"The static field superLargeBook.maxAmountOfPages should be accessed in a static
way" . What is meant by this? Well, it means that it's generally preferred to access and modify static
variables not by accessing them through an object variable, but by using the class name directly, like
so:
Book.maxAmountOfPages = 2000; // Let's increase the max amount of pages
System.out.println("We now support books with max. pages: "
+Book.maxAmountOfPages);
Accessing and modifying static variables in this manner has two benefits. First, you do not need
to create an object in order to access the static variable. Second, this way makes it clear to
readers that the variable being accessed is a static one, without them needing to read the class
definition. Finally, speaking of class definitions, it's generally a good idea to define class vari-
ables before defining instance variables when you write classes, just to keep things clean and
readable.
Static variables are oftentimes used to define so‐called constants: variables whose values will never
change during the execution of a program. However, as you have seen, it is perfectly okay to change
the maximum amount of pages by setting a new value to Book.maxAmountOfPages . If you want to
keep variables fixed during the program's execution, you need to consider another concept: final
variables.
final variables
In Java, final variables are variables that can be initialized only once, either directly when defining
the variable, or later in one of the class methods. Once a value has been given to the variable, how-
ever, it cannot be modified any longer.
You can see an example of a final variable by returning to the book class and modifying it a little, so
the complete class looks as follows:
class Book {
final String title = "Unknown Title";
String[] authors = new String[]{"Anonymous"};
int yearReleased = 2014, copiesSold = 0, nrOfPages;
public static void main(String[] args) {
Book superLargeBook = new Book();
superLargeBook.title = "Super Large Boring Book";
superLargeBook.nrOfPages = 1400;
}
}
Note the change to the title variable, as it now has the final property. To keep things simple for
now, I have also removed the static variable and have put some testing code in a main method, so
you can execute this class.
 
Search WWH ::




Custom Search