Java Reference
In-Depth Information
properly initialized for all instances of Movie , and the initialization takes place in a single
location (instead of in multiple constructors).
The code on the exam uses a lot of explicit initialization. This is probably
because it makes the code shorter and simpler. Often the exam question
will likely be testing your knowledge of a topic not specifically related
to explicit initialization, so explicit initialization is one of those fundamental
concepts you are just expected to know.
Class Variables
A class variable is a fi eld within a class declared as static, often referred to as a static
variable or static fi eld . A static fi eld is unique in that the memory is allocated for the fi eld
when the class is loaded by the JVM's class loader, and the variable remains in memory
until the class loader unloads the class. Because a program typically terminates before a
class is unloaded, the lifetime of a static fi eld is often the lifetime of the application.
Static fi elds do not belong to instances of a class. You can access a static fi eld before any
instances of the class are created, and if you have 100 instances of the class, you still only
have one instance of the static fi eld.
Global Variables in Java
Java does not support the concept of global variables. All variables in Java appear within
a class or interface. Static fi elds are the closest thing you have in Java to global variables,
because a static fi eld has a lifetime beyond the life of the instances of the class and a
static fi eld can be accessed from any other class or object (depending on the access
specifi er).
Consider the following class named House with a static int fi eld named counter :
1. package my.blueprints;
2. public class House {
3. private Room kitchen; //instance variable
4. public static int counter = 0; //class variable
5.
6. public House() {
7. kitchen = new Room();
8. }
Search WWH ::




Custom Search