Java Reference
In-Depth Information
Similarly, what happens if there are 100 Employee objects in memory? There are 100
name fields in memory. Which name am I setting equal to “Rich?” All of them? That would
be an interesting company to work for. Again, it does not make sense to set name equal to
“Rich” because it is not clear which name is being changed.
For these reasons, static methods cannot access nonstatic fields or methods. It does
not make any sense, as we can see with trying to change the name field to “Rich.” Also,
accessing a nonstatic member requires the this reference. Static methods do not have a
this reference.
Therefore, static methods cannot access nonstatic fields. The statement:
name = “Rich”;
does not compile in the static getCounter() method. The compiler generates the following
error:
Employee.java:26: non-static variable name cannot be
referenced from a static context
name = “Rich”;
^
1 error
This compiler error would have occurred whether or not the this reference was explicitly
used to access name.
Static Initializers
The static keyword has another use outside of declaring a field or method static.
A Java class can contain a static initializer, which is a group of statements that
execute when the class is being loaded by the class loader of the JVM.
Classes are loaded once by the class loader, and the purpose of a static ini-
tializer is to allow the class to perform any necessary setup tasks that would
only need to occur once.
A static initializer is declared by using the static keyword followed by a set
of curly brackets to enclose the statements of the initializer:
static {
//Statements appear here.
}
The following Radio class contains a static initializer.
public class Radio
{
private int station;
public Radio(int x)
{
System.out.println(“Constructing a Radio”);
Search WWH ::




Custom Search