Java Reference
In-Depth Information
Understanding Static Fields
I often refer to static fi elds as breaking the rules of object-oriented programming. I am
not implying that static should be avoided, because static fi elds are an important part
of the Java language and I use them all the time. However, it is important to understand
what it means for a fi eld to be static. It might seem odd that a fi eld of a class can exist
before the class is ever instantiated. Recall my analogy of a class being the blueprint of a
house, and an object being the house. If we make the kitchen static, that means we have
a kitchen before we ever build the house! In addition, if we build 100 houses from our
blueprint, we still only have one kitchen! Obviously a kitchen is not a good candidate for
static when it comes to building houses.
We use static fi elds when the fi eld is shared among all classes and the fi eld is not unique
to any particular instance. For example, the House class can keep track of how many
times a particular method is invoked on all House objects. Because counter is shared
among all House objects, this is a perfect situation for using a static fi eld.
Global variables are another common example of when to use static. For example, there
is only one standard input and standard output. Making them global variables allows
all objects in your program to access the standard input and output, so System.in and
System.out are good candidates for static fi elds.
Static Imports
As of Java 5.0, a static variable can be imported into a source fi le, which allows the static
variable to be accessible without being prefi xed with its corresponding class or interface name.
Importing a static member is referred to as a static import and uses the following syntax:
import static packagenames.classname.variablename ;
You can also use the asterisk as a wildcard, which allows you to import all of the static
variables from a class or interface. Static imports appear in the same location of a source
fi le as regular imports: after the package declaration and before the class declaration.
The following program is the same code as the HouseTest program in the previous
example, except the static fi eld counter from House is imported on line 3. The class also
imports all static fi elds in java.lang.System on line 4, which includes the out fi eld.
1. import my.blueprints.House;
2.
3. import static my.blueprints.House.counter;
4. import static java.lang.System.*;
5.
6. public class StaticImportDemo {
Search WWH ::




Custom Search