8.3.1
Field Modifiers
CLASSES
q.origin==Point.origin
is
true
. Further evidence is that the incrementation:
p.origin.useCount++;
causes the value of
q.origin.useCount
to be
1
; this is so because
p.origin
and
q.origin
refer to the same variable.
8.3.1.2
final
Fields
A field can be declared
final
, in which case its declarator must include a variable
initializer or a compile time error occurs. Both class and instance variables
(
static
and non
static
fields) may be declared
final
.
Any attempt to assign to a
final
field results in a compile time error. There
fore, once a
final
field has been initialized, it always contains the same value. If
a
final
field holds a reference to an object, then the state of the object may be
changed by operations on the object, but the field will always refer to the same
object. This applies also to arrays, because arrays are objects; if a
final
field
holds a reference to an array, then the components of the array may be changed by
operations on the array, but the field will always refer to the same array.
Declaring a field
final
can serve as useful documentation that its value will
not change, can help to avoid programming errors, and can make it easier for a
compiler to generate efficient code.
In the example:
class Point {
int x, y;
int useCount;
Point(int x, int y) { this.x = x; this.y = y; }
final static Point origin = new Point(0, 0);
}
the class
Point
declares a
final
class variable
origin
. The
origin
variable
holds a reference to an object that is an instance of class
Point
whose coordinates
are (0, 0). The value of the variable
Point.origin
can never change, so it always
refers to the same
Point
object, the one created by its initializer. However, an
operation on this
Point
object might change its state for example, modifying its
useCount
or even, misleadingly, its
x
or
y
coordinate.
8.3.1.3
transient
Fields
Variables may be marked
transient
to indicate that they are not part of the per
sistent state of an object. If an instance of the class
Point
:
146
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved