Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces


Declaring a Member Variable

A class contains its state within its member variables. This section tells you everything you need to know to declare member variables for your Java classes. For more information about how to access those variables see Using an Object.

You declare a class's member variables with the body of the class. Typically, you declare a class's variables before you declare its methods, although this is not required.

classDeclaration {
    . . .
    member variable declarations
    . . .
    method declarations
    . . .
}
Note: To declare variables that are a member of a class, the declarations must be within the class body, but not within the body of a method. Variables declared within the body of a method are local to that method.

At minimum, a member variable declaration has two components: the type of the variable and its name.

type variableName;	// minimal member variable declaration
For example, the following code snippet declares an integer member variable named anInteger within the class IntegerClass.
class IntegerClass {
    int anInteger;	// bare-bones member variable declaration
}
When you declare a variable like this, you declare an instance variable. An instance variable occurs once per instance of a class; that is, every time you create a new instance of the class, the system allocates memory for all of the class's instance variables. This is in constrast to class variables which occur once per class regardless of the number of instances created of that class. The system allocates memory for class variables the first time it encounters the class. All instances share the same copy of the class's class variables. For information about instance and class variables, see The Scoop on Instance and Class Variables The Method Body.

Other Variable Declaration Components

Besides type and name, there are several other variable attributes that you can specify when declaring a member variable. These include such attributes as whether other objects can access the variable, whether the variable is a class or instance variable and whether the variable is a constant.

Follow these links to find more information about

Summary

In summary, a member variable declaration looks like this:
[accessSpecifier] [static] [final] [transient] [volatile] type variableName
The items between [ and ] are optional. Italic items are to be replaced by keywords or names.

A variable declaration defines the following aspects of the variable:


Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces