CHAPTER 8: Class Declarations Previous
Previous
Java Language
Java Language
Index
Index
Next
Next

8.3 Field Declarations

8.3.1 Field Modifiers , 8.3.2 Initialization of Fields , 8.3.3 Examples of Field Declarations

The variables of a class type are introduced by field declarations:


FieldDeclaration:

	FieldModifiersopt Type VariableDeclarators ;

VariableDeclarators:

	VariableDeclarator

	VariableDeclarators , VariableDeclarator

VariableDeclarator:

	VariableDeclaratorId

	VariableDeclaratorId = VariableInitializer

VariableDeclaratorId:

	Identifier

	VariableDeclaratorId [ ]

VariableInitializer:

	Expression

	ArrayInitializer

The FieldModifiers are described in S8.3.1. The Identifier in a FieldDeclarator may be used in a name to refer to the field. The name of a field has as its scope (S6.3) the entire body of the class declaration in which it is declared. More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration. Variable declarations involving array types are discussed in S10.2.

It is a compile-time error for the body of a class declaration to contain declarations of two fields with the same name. Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (S6.5).

If the class declares a field with a certain name, then the declaration of that field is said to hide (S6.3.1) any and all accessible declarations of fields with the same name in the superclasses and superinterfaces of the class.

If a field declaration hides the declaration of another field, the two fields need not have the same type.

A class inherits from its direct superclass and direct superinterfaces all the fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

It is possible for a class to inherit more than one field with the same name (S8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.

There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.

A hidden field can be accessed by using a qualified name (if it is static ) or by using a field access expression (S15.10) that contains the keyword super or a cast to a superclass type. See S15.10.2 for discussion and an example.


8.3.1 Field Modifiers


FieldModifiers:

	FieldModifier

	FieldModifiers FieldModifier

FieldModifier: one of

	public protected private

	final static transient volatile

The access modifiers public , protected , and private are discussed in S6.6. A compile-time error occurs if the same modifier appears more than once in a field declaration, or if a field declaration has more than one of the access modifiers public , protected , and private . If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.

8.3.1.1 static Fields

If a field is declared static , there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (S12.4).

A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.

The example program:


class Point {
	int x, y, useCount;
	Point(int x, int y) { this.x = x; this.y = y; }
	final static Point origin = new Point(0, 0);
}


class Test {
	public static void main(String[] args) {
		Point p = new Point(1,1);
		Point q = new Point(2,2);
		p.x = 3; p.y = 3; p.useCount++; p.origin.useCount++;
		System.out.println("(" + q.x + "," + q.y + ")");
		System.out.println(q.useCount);
		System.out.println(q.origin == Point.origin);
		System.out.println(q.origin.useCount);
	}
}

prints:


(2,2)
0
true
1

showing that changing the fields x , y , and useCount of p does not affect the fields of q , because these fields are instance variables in distinct objects. In this example, the class variable origin of the class Point is referenced both using the class name as a qualifier, in Point.origin , and using variables of the class type in field access expressions (S15.10), as in p.origin and q.origin . These two ways of accessing the origin class variable access the same object, evidenced by the fact that the value of the reference equality expression (S15.20.3):

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. Therefore, 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 persistent state of an object. If an instance of the class Point :


class Point {
	int x, y;
	transient float rho, theta;
}

were saved to persistent storage by a system service, then only the fields x and y would be saved. This specification does not yet specify details of such services; we intend to provide them in a future version of this specification.

8.3.1.4 volatile Fields

As described in Chapter 17, the Java language allows threads that access shared variables to keep private working copies of the variables; this allows a more efficient implementation of multiple threads. These working copies need be reconciled with the master copies in the shared main memory only at prescribed synchronization points, namely when objects are locked or unlocked. As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

Java provides a second mechanism that is more convenient for some purposes: a field may be declared volatile , in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.

If, in the following example, one thread repeatedly calls the method one (but no more than Integer.MAX_VALUE (S20.7.2) times in all), and another thread repeatedly calls the method two :


class Test {

	static int i = 0, j = 0;


	static void one() { i++; j++; }

	static void two() {
		System.out.println("i=" + i + " j=" + j);
	}

}

then method two could occasionally print a value for j that is greater than the value of i , because the example includes no synchronization and, under the rules explained in Chapter 17, the shared values of i and j might be updated out of order.

One way to prevent this out-or-order behavior would be to declare methods one and two to be synchronized (S8.4.3.5):


class Test {

	static int i = 0, j = 0;


	static synchronized void one() { i++; j++; }

	static synchronized void two() {
		System.out.println("i=" + i + " j=" + j);
	}

}

This prevents method one and method two from being executed concurrently, and furthermore guarantees that the shared values of i and j are both updated before method one returns. Therefore method two never observes a value for j greater than that for i ; indeed, it always observes the same value for i and j .

Another approach would be to declare i and j to be volatile :


class Test {

	static volatile int i = 0, j = 0;


	static void one() { i++; j++; }

	static void two() {
		System.out.println("i=" + i + " j=" + j);
	}

}

This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, method two never observes a value for j greater than that for i , because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i , because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j .

See Chapter 17 for more discussion and examples.

A compile-time error occurs if a final variable is also declared volatile .


8.3.2 Initialization of Fields

If a field declarator contains a variable initializer, then it has the semantics of an assignment (S15.25) to the declared variable, and:

The example:


class Point {
	int x = 1, y = 5;
}

class Test {
	public static void main(String[] args) {
		Point p = new Point();
		System.out.println(p.x + ", " + p.y);
	}
}

produces the output:

1, 5

because the assignments to x and y occur whenever a new Point is created.

Variable initializers are also used in local variable declaration statements (S14.3), where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.

It is a compile-time error if the evaluation of a variable initializer for a field of a class (or interface) can complete abruptly with a checked exception (S11.2).

8.3.2.1 Initializers for Class Variables

A compile-time error occurs if an initialization expression for a class variable contains a use by a simple name of that class variable or of another class variable whose declaration occurs to its right (that is, textually later) in the same class. Thus:


class Test {
	static float f = j;							// compile-time error: forward reference
	static int j = 1;
	static int k = k+1;							// compile-time error: forward reference
}

causes two compile-time errors, because j is referred to in the initialization of f before j is declared and because the initialization of k refers to k itself.

If a reference by simple name to any instance variable occurs in an initialization expression for a class variable, then a compile-time error occurs.

If the keyword this (S15.7.2) or the keyword super (S15.10.2, S15.11) occurs in an initialization expression for a class variable, then a compile-time error occurs.

(One subtlety here is that, at run time, static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (S9.3.1). These variables are "constants" that will never be observed to have their default initial values (S4.5.4), even by devious programs. See S12.4.2 and S13.4.8 for more discussion.)

8.3.2.2 Initializers for Instance Variables

A compile-time error occurs if an initialization expression for an instance variable contains a use by a simple name of that instance variable or of another instance variable whose declaration occurs to its right (that is, textually later) in the same class. Thus:


class Test {
	float f = j;
	int j = 1;
	int k = k+1;
}

causes two compile-time errors, because j is referred to in the initialization of f before j is declared and because the initialization of k refers to k itself.

Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later. Thus the example:


class Test {
	float f = j;
	static int j = 1;
}

compiles without error; it initializes j to 1 when class Test is initialized, and initializes f to the current value of j every time an instance of class Test is created.

Initialization expressions for instance variables are permitted to refer to the current object this (S15.7.2) and to use the keyword super (S15.10.2, S15.11).


8.3.3 Examples of Field Declarations

The following examples illustrate some (possibly subtle) points about field declarations.

8.3.3.1 Example: Hiding of Class Variables

The example:


class Point {
	static int x = 2;
}


class Test extends Point {
	static double x = 4.7;
	public static void main(String[] args) {

		new Test().printX();
	}
	void printX() {
		System.out.println(x + " " + super.x);
	}
}

produces the output:

4.7 2

because the declaration of x in class Test hides the definition of x in class Point , so class Test does not inherit the field x from its superclass Point . Within the declaration of class Test , the simple name x refers to the field declared within class Test . Code in class Test may refer to the field x of class Point as super.x (or, because x is static , as Point.x ). If the declaration of Test.x is deleted:


class Point {
	static int x = 2;
}


class Test extends Point {
	public static void main(String[] args) {
		new Test().printX();
	}
	void printX() {
		System.out.println(x + " " + super.x);
	}
}

then the field x of class Point is no longer hidden within class Test ; instead, the simple name x now refers to the field Point.x . Code in class Test may still refer to that same field as super.x . Therefore, the output from this variant program is:

2 2


8.3.3.2 Example: Hiding of Instance Variables

This example is similar to that in the previous section, but uses instance variables rather than static variables. The code:


class Point {
	int x = 2;
}


class Test extends Point {
	double x = 4.7;
	void printBoth() {
		System.out.println(x + " " + super.x);
	}
	public static void main(String[] args) {
		Test sample = new Test();
		sample.printBoth();
		System.out.println(sample.x + " " + 

												((Point)sample).x);
	}
}

produces the output:


4.7 2
4.7 2

because the declaration of x in class Test hides the definition of x in class Point , so class Test does not inherit the field x from its superclass Point . It must be noted, however, that while the field x of class Point is not inherited by class Test , it is nevertheless implemented by instances of class Test . In other words, every instance of class Test contains two fields, one of type int and one of type float . Both fields bear the name x , but within the declaration of class Test , the simple name x always refers to the field declared within class Test . Code in instance methods of class Test may refer to the instance variable x of class Point as super.x .

Code that uses a field access expression to access field x will access the field named x in the class indicated by the type of reference expression. Thus, the expression sample.x accesses a float value, the instance variable declared in class Test , because the type of the variable sample is Test , but the expression ((Point)sample).x accesses an int value, the instance variable declared in class Point , because of the cast to type Point .

If the declaration of x is deleted from class Test , as in the program:


class Point {
	static int x = 2;
}


class Test extends Point {
	void printBoth() {
		System.out.println(x + " " + super.x);
	}
	public static void main(String[] args) {
		Test sample = new Test();
		sample.printBoth();
		System.out.println(sample.x + " " +

												((Point)sample).x);
	}
}

then the field x of class Point is no longer hidden within class Test . Within instance methods in the declaration of class Test , the simple name x now refers to the field declared within class Point . Code in class Test may still refer to that same field as super.x . The expression sample.x still refers to the field x within type Test , but that field is now an inherited field, and so refers to the field x declared in class Point . The output from this variant program is:


2 2
2 2


8.3.3.3 Example: Multiply Inherited Fields

A class may inherit two or more fields with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited field by its simple name. A qualified name or a field access expression that contains the keyword super (S15.10.2) may be used to access such fields unambiguously. In the example:


interface Frob { float v = 2.0f; }


class SuperTest { int v = 3; }



class Test extends SuperTest implements Frob {
	public static void main(String[] args) {
		new Test().printV();
	}
	void printV() { System.out.println(v); }
}

the class Test inherits two fields named v , one from its superclass SuperTest and one from its superinterface Frob . This in itself is permitted, but a compile-time error occurs because of the use of the simple name v in method printV : it cannot be determined which v is intended.

The following variation uses the field access expression super.v to refer to the field named v declared in class SuperTest and uses the qualified name Frob.v to refer to the field named v declared in interface Frob :


interface Frob { float v = 2.0f; }


class SuperTest { int v = 3; }



class Test extends SuperTest implements Frob {
	public static void main(String[] args) {
		new Test().printV();
	}
	void printV() {
		System.out.println((super.v + Frob.v)/2);
	}
}

It compiles and prints:

2.5

Even if two distinct inherited fields have the same type, the same value, and are both final , any reference to either field by simple name is considered ambiguous and results in a compile-time error. In the example:


interface Color { int RED=0, GREEN=1, BLUE=2; }


interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; }



class Test implements Color, TrafficLight {
	public static void main(String[] args) {
		System.out.println(GREEN);										// compile-time error
		System.out.println(RED);										// compile-time error
	}
}

it is not astonishing that the reference to GREEN should be considered ambiguous, because class Test inherits two different declarations for GREEN with different values. The point of this example is that the reference to RED is also considered ambiguous, because two distinct declarations are inherited. The fact that the two fields named RED happen to have the same type and the same unchanging value does not affect this judgment.

8.3.3.4 Example: Re-inheritance of Fields

If the same field declaration is inherited from an interface by multiple paths, the field is considered to be inherited only once. It may be referred to by its simple name without ambiguity. For example, in the code:


public interface Colorable {
	int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff;
}


public interface Paintable extends Colorable {
	int MATTE = 0, GLOSSY = 1;
}


class Point { int x, y; }


class ColoredPoint extends Point implements Colorable {
	. . .
}


class PaintedPoint extends ColoredPoint implements Paintable 
{
	. . .       RED       . . .
}

the fields RED , GREEN , and BLUE are inherited by the class PaintedPoint both through its direct superclass ColoredPoint and through its direct superinterface Paintable . The simple names RED , GREEN , and BLUE may nevertheless be used without ambiguity within the class PaintedPoint to refer to the fields declared in interface Colorable .

Top© 1996 Sun Microsystems, Inc. All rights reserved.