Navigation:  Tutorials > Beginners Guide to Smalltalk > Classes and Methods >

Indexed Instance Variables

Previous pageReturn to chapter overviewNext page

For some classes of object, normally those that hold collections of other objects, it is not convenient to simply use named instance variable slots for the object's storage. Hopefully you can see why, since you might need hundreds of separately named variables and even different numbers of variables depending on how many objects you wanted to hold on to. For this reason, certain classes are allowed to have indexed instance variables associated with them.

Each of the instance variable slots is accessible using an integer index. This makes an object that uses indexed variables very much like an array in most other programming languages. The index of the first slot is one, so we generally say that Smalltalk indexes are one-based (rather than zero-based).

The number of available indexed variables can be altered dynamically by sending the object a #resize: message with an integer parameter containing the number of slots required. This makes it very easy to implement classes that can hold collections of other objects. Smalltalk comes complete with a very powerful set of collection classes. For the moment, let's just take a look at the class definition of a common collection class in the base image. Using the Class Browser, find the class called Array (remember you need to select the top left-hand pane and type Ctrl+F). You should see the following class definition displayed:

ArrayedCollection variableSubclass: #Array

       instanceVariableNames: ''

       classVariableNames: ''

       poolDictionaries: ''


The class is being defined using a single message with a rather lengthy selector, #variableSubclass:instanceVariableNames:classVariableNames:poolDictionaries:. This message is being sent to the class called ArrayedCollection on which the new class Array is to be based. Note the difference between this definition and the one for Point. There are no named instance variables required here and, in addition, there is the use of variableSubclass: as part of the message selector rather than just plain old subclass:. Now, without going into too much detail at this stage, you just need to take away from this that the Array class is being defined as having a variable number of indexed instance variable slots rather than a fixed number of named instance variables.