Skip to main content
ICT
Lesson A5 - Designing and Using Classes
 
Main   Previous Next
 

C. Instance Variables page 5 of 11

  1. Before any code can be written for the behaviors, the object must know how to store its current state. The state is the set of attributes that describes the object and that influences how an object reacts to method calls. In the case of our checking account objects, the state includes the current balance and an account identifier.

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

  2. An instance variable declaration consists of the following parts:

    access_specifier type variable_name

    1. The access_specifier (such as private) tells who can access that data member. Instance variables are generally declared with the access specifier private. That means they can be accessed only by methods of the same class. 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).

  3. If instance variables are declared private, then all external data access must occur through the non-private methods. This means that the instance variables of an object are hidden. 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. In this curriculum, instance variables will always be made private.

  4. For example, because the myBalance instance variable is private, it cannot be accessed from outside of the class:

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

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

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

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.