Java Reference
In-Depth Information
Examine the following statements and try to determine the output:
3. Television tv = new Television();
4. System.out.println(tv.channel + “ “ + tv.diagonal + “ “ + tv.brand);
The preceding code compiles fi ne. The channel fi eld is initially 0 but is set to 4 in the
constructor. The diagonal fi eld is a double so its initial value is 0.0. The brand fi eld is a
reference so its value is null . The output is
4 0.0 null
Figure 2.1 shows what this Television object looks like in memory.
FIGURE 2.1 A Television object has three fields in memory.
Television reference
Television object
tv
channel
4
diagonal
0.0
brand
null
The Lifetime of Instance Variables
An instance variable does not exist in memory until an instance of the class is
instantiated. When an object is instantiated, its instance variables exist in memory until
the object is garbage collected.
Explicit Initialization
Java allows for the explicit initialization of instance variables. Explicit initialization
is when a fi eld is assigned a value at the same time that the fi eld is declared. The fi eld
therefore gets initialized before the constructor executes.
Search WWH ::




Custom Search