29.11.2014 Views

Smalltalk and Object Orientation: an Introduction - Free

Smalltalk and Object Orientation: an Introduction - Free

Smalltalk and Object Orientation: an Introduction - Free

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The OrderedCollection class c<strong>an</strong> be used to construct a Stack or Queue class. An example<br />

of how to do this is presented in the next section. Notice how little code has to be written <strong><strong>an</strong>d</strong> how much<br />

is inherited.<br />

10.8 Stack <strong><strong>an</strong>d</strong> queue classes in <strong>Smalltalk</strong><br />

In this section we will work t hrough <strong>an</strong> example illustrating how we c<strong>an</strong> define new collection classes<br />

(data structures). We shall put both classes we will define into a class category called “Additional -<br />

Collections”.<br />

10.8.1 The Stack class<br />

The first class we will define is the Stack class. Th e class definition of the Stack is illustrated<br />

below 9 . Note that we are making Stack a subclass of OrderedCollection. This is because the<br />

elements of a stack are ordered, <strong><strong>an</strong>d</strong> may be duplicated within the stack. Also note that we are not<br />

defining <strong>an</strong>y new in st<strong>an</strong>ce variables. The functionality of the Stack will come solely from extending<br />

the interface, the structure of the class will be completely inherited from the OrderedCollection<br />

class.<br />

OrderedCollection variableSubclass: #Stack<br />

inst<strong>an</strong>ceVariableNames: ''<br />

classVariableNames: ''<br />

poolDictionaries: ''<br />

category: 'Additional-Collections'<br />

As before I am also providing a class comment (see Figure 10.4). Again it is up to you to decide<br />

whether you wish to provide one as well (although I strongly recommend doing so - it is a good habit to<br />

get into).<br />

Figure 10.4: The Stack class comment<br />

9<br />

As OrderedCollections are variable in size the variableSub class: class creation message is used. Don't worry too much<br />

about this as the tools provided with environments such as VisualWorks ensure that the appropriate message is always used.<br />

92

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!