Java Reference
In-Depth Information
constants that javac may inline. final fields can also be used to create classes
whose instances are immutable.
This modifier specifies that a field is not part of the persistent state of an object
and that it need not be serialized along with the rest of the object.
This modifier indicates that the field has extra semantics for concurrent use by
two or more threads. The volatile modifier says that the value of a field must
always be read from and flushed to main memory, and that it may not be
cached by a thread (in a register or CPU cache). See Chapter 6 for more details.
Class Fields
A class ield is associated with the class in which it is defined rather than with an
instance of the class. The following line declares a class field:
public static final double PI = 3.14159 ;
This line declares a field of type double named PI and assigns it a value of 3.14159.
The static modifier says that the field is a class field. Class fields are sometimes
called static fields because of this static modifier. The final modifier says that the
value of the field does not change. Because the field PI represents a constant, we
declare it final so that it cannot be changed. It is a convention in Java (and many
other languages) that constants are named with capital letters, which is why our
field is named PI , not pi . Defining constants like this is a common use for class
fields, meaning that the static and final modifiers are often used together. Not all
class fields are constants, however. In other words, a field can be declared static
without being declared final .
The use of public static fields that are not final is almost
never a good practice—as multiple threads could update the
field and cause behavior that is extremely hard to debug.
A public static field is essentially a global variable. The names of class fields are
qualified by the unique names of the classes that contain them, however. Thus, Java
does not suffer from the name collisions that can affect other languages when differ‐
ent modules of code define global variables with the same name.
The key point to understand about a static field is that there is only a single copy of
it. This field is associated with the class itself, not with instances of the class. If you
look at the various methods of the Circle class, you'll see that they use this field.
From inside the Circle class, the field can be referred to simply as PI . Outside the
class, however, both class and field names are required to uniquely specify the field.
Methods that are not part of Circle access this field as Circle.PI .
Search WWH ::

Custom Search