Java Reference
In-Depth Information
StaticDemo sd2 = new StaticDemo();
System.out.println(sd1.oneValueForAllObjects);
System.out.println(sd2.oneValueForAllObjects);
sd1.oneValueForAllObjects = true;
System.out.println(sd1.oneValueForAllObjects);
System.out.println(sd2.oneValueForAllObjects);
}
}
Listing 1-4 produces the following output:
false
false
true
true
The field oneValueForAllObjects was set to true only for the class in-
stance named sd1 . Yet it is true for instance sd2 also. This is because of the keyword
static used in declaring that field. Static fields occur one time for all objects of their
class.
How It Works
Listing 1-2 illustrates the basic format of a variable declaration:
type variable;
It's common to initialize variables when declaring them, so you'll often see:
type variable = initialValue;
Field declarations can be preceded by modifiers. For example:
public static variable = initialValue;
private variable;
Search WWH ::




Custom Search