Java Reference
In-Depth Information
Employees after instantiation:
via e1.getCount(): 2
via e2.getCount(): 2
via Employee.getCount(): 2
Employee 1: Susan Baker
Employee 2: Bob Blue
Fig. 8.13 | static member demonstration. (Part 2 of 2.)
When main terminates, local variables e1 and e2 are discarded—remember that a local
variable exists only until the block in which it's declared completes execution. Because e1
and e2 were the only references to the Employee objects created in lines 13-14 (Fig. 8.13),
these objects become “eligible for garbage collection” as main terminates.
In a typical app, the garbage collector might eventually reclaim the memory for any
objects that are eligible for collection. If any objects are not reclaimed before the program
terminates, the operating system will reclaim the memory used by the program. The JVM
does not guarantee when, or even whether, the garbage collector will execute. When it
does, it's possible that no objects or only a subset of the eligible objects will be collected.
8.12 static Import
In Section 6.3, you learned about the static fields and methods of class Math . We access
class Math 's static fields and methods by preceding each with the class name Math and a
dot ( . ). A static import declaration enables you to import the static members of a class
or interface so you can access them via their unqualified names in your class—that is, the
class name and a dot ( . ) are not required when using an imported static member.
static Import Forms
A static import declaration has two forms—one that imports a particular static mem-
ber (which is known as single static import ) and one that imports all static members
of a class (known as static import on demand ). The following syntax imports a particular
static member:
import static packageName . ClassName . staticMemberName ;
where packageName is the package of the class (e.g., java.lang ), ClassName is the name of
the class (e.g., Math ) and staticMemberName is the name of the static field or method
(e.g., PI or abs ). The following syntax imports all static members of a class:
import static packageName . ClassName .*;
The asterisk ( * ) indicates that all static members of the specified class should be available
for use in the file. static import declarations import only static class members. Regular
import statements should be used to specify the classes used in a program.
Demonstrating static Import
Figure 8.14 demonstrates a static import. Line 3 is a static import declaration, which
imports all static fields and methods of class Math from package java.lang . Lines 9-12
access the Math class's static fields E (line 11) and PI (line 12) and the static methods
 
 
Search WWH ::




Custom Search