![]() ![]() ![]() ![]() |
Objects, Classes, and Interfaces |
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.
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.classDeclaration { . . . member variable declarations . . . method declarations . . . }At minimum, a member variable declaration has two components: the type of the variable and its name.
For example, the following code snippet declares an integer member variable namedtype variableName; // minimal member variable declarationanInteger
within the classIntegerClass
.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.class IntegerClass { int anInteger; // bare-bones member variable declaration }
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
In summary, a member variable declaration looks like this:The items between [ and ] are optional. Italic items are to be replaced by keywords or names.[accessSpecifier] [static] [final] [transient] [volatile] type variableNameA variable declaration defines the following aspects of the variable:
- accessSpecifier defines which other classes have access to the variable
static
indicates that the variable is a class member variable as opposed to an instance member variablefinal
indicates that the variable is a constanttransient
variables are not part of the object's persistent statevolatile
means that the variable is modified asynchronously
![]() ![]() ![]() ![]() |
Objects, Classes, and Interfaces |