Java Reference
In-Depth Information
The use of System.out itself illustrates accessing a static field. When a
static member of a class is referenced many times from another class,
or when multiple static members of a class are referenced from another
class, you can clarify the code, and perhaps save some typing, by using
a static import statement to name the class of the static member once.
This is discussed in detail in Section 2.9 on page 71 .
A static member may also be accessed using a reference to an object of
that class, such as
System.out.println(mercury.nextID);
You should avoid this form because it gives the false impression that
nextID is a member of the object mercury , not a member of the class Body .
It is the type of the reference, not the type of the object it refers to, that
determines the class in which to look for the static variable.
In this topic when we use the term field, we usually mean the non-static
kind. When the context makes it ambiguous, we use the term non-static
field to be clear.
Exercise 2.3 : Add a static field to your Vehicle class to hold the next
vehicle identification number, and a non-static field to the Vehicle class
to hold each car's ID number.
2.2.3. final Fields
A final variable is one whose value cannot be changed after it has been
initializedany attempt to assign to such a field will produce a compile-
time error. We have seen final fields used to define named constants
because constants don't change value. In general, a final field is used to
define an immutable property of a class or objecta property that doesn't
change for the lifetime of the class or object. Fields that are marked
final also have special semantics with regard to concurrent access by
multiple threads, this is discussed in more detail in Chapter 14 .
 
Search WWH ::




Custom Search