Instance Variable (7.6.3)

Problem:

An object needs to maintain a value. The value must be remembered for longer than just one method call (when a temporary variable would be appropriate). The value is usually needed in more than one method.

Solution:

Use an instance variable. Instance variables are declared within the class, but outside of all the methods. Examples of instance variables include

private int numMoves = 0;
private double balance = 0.0;
private long creditCardNumber;  

An instance variable is declared with one of two general forms:

«visibility» «type» «name» = «initialValue»
«visibility» «type» «name»

where «visibility» is usually private, and «type» is the type of the variable. Examples include int, double , boolean, and names of classes such as Robot. «name;» is the name used to refer to the value stored. The variable's initial value should be established either in the declaration, as shown in the first form, or assigned in the constructor. Assign the initial value on the declaration if all instances of this class start with the same value. Assign it in the constructor if each instance will have its initial value supplied by parameters to a constructor.

An instance variable may be accessed within methods or constructors with the implicit parameter, this, followed by a dot and the name of the variable. It may also be accessed by just giving the name of the variable if the name is not the same as a parameter or temporary variable.

An instance variable should not be used when the value is only used within a single method. In that case, use a temporary variable.

Consequences:

An instance variable stores a value for the lifetime of the object or until it is explicitly changed by an assignment statement.