Skip to main content
Lesson 6 - Defining and Using Classes
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Instance Variables page 5 of 11

  1. Each object must store its current state. The state is the set of values that describe the object and that influence how an object reacts to method calls. In the case of our checking account objects, the state is the current balance and an account identifier.

  2. Each object stores its state in one or more instance variables.

    public class CheckingAccount
    {
      ...
      private double myBalance;
      private String myAccountNumber;
    
      // CheckingAccount methods
    }
  3. An instance variable declaration consists of the following parts:

    access_specifier type variable_name
    1. An access specifier (such as private). Instance variables are generally declared with the access specifier private. That means they can be accessed only by methods of the same class, not by any other method. In particular, the balance variable can be accessed only by the deposit, withdraw, and getBalance methods.

    2. The type of the variable (such as double).

    3. The variable_name (such as myBalance).

    Figure 6-2. Instance Variables

  4. If instance variables are declared private, then all data access must occur through the public methods. This means that the instance variables of an object are effectively hidden from the programmer who only uses a class. They are available only to the programmer who implements the class, that is, the one who writes or revises the methods. The process of hiding data is called encapsulation. Although it is possible in Java to define instance variables as public (leave them unencapsulated), it is very uncommon in practice. We will usually make instance variables private in this curriculum guide.

  5. For example, because the myBalance instance variable is private, it cannot be accessed in other code:

    double balance = checking.mybalance;  // compiler ERROR!

    However, the public getBalance method to inquire about the balance can be called:

    double balance = checking.getBalance();  // OK

Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.