Skip to main content
ICT
Lesson A5 - Designing and Using Classes
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

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.