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.

this convention at the moment, however it is used throughout <strong>Smalltalk</strong> , it is therefore advisable to use<br />

it.<br />

age: <strong>an</strong>Integer<br />

"This method sets age."<br />

age := <strong>an</strong>Integer<br />

This method illustrates <strong>an</strong>other feature of <strong>Smalltalk</strong> programming style, the use of class names as<br />

parameter variable names. For example, in this method we a re expecting one parameter. <strong>Smalltalk</strong> is<br />

untyped, therefore the contents of this parameter could be <strong>an</strong>ything. However, the programmer of this<br />

method has indicated to us that they expect the value passed into the method to be <strong>an</strong> integer. At least<br />

now, if the system encounters a run time error <strong><strong>an</strong>d</strong> we enter the debugger, we c<strong>an</strong> see if the contents of<br />

<strong>an</strong>Integer is <strong>an</strong> integer or not. If it is not, then we may have found the source of the problem.<br />

Figure 8.3: The System Browser displaying part of the Person definition<br />

The equivalent methods for accessing <strong><strong>an</strong>d</strong> updating the value of the inst<strong>an</strong>ce variable name are<br />

presented below. They are very simple <strong><strong>an</strong>d</strong> should not come as a surprise. They are therefore mer ely<br />

listed <strong><strong>an</strong>d</strong> are not discussed in detail.<br />

name<br />

"This retrieves the contents of name."<br />

^name<br />

name: aString<br />

"This sets the contents of name."<br />

name := aString<br />

8.3.3 The “updating” protocol<br />

Having defined all the methods for the “accessing” protocol, we will now define a new protocol called<br />

“updating”. This protocol should be created in exactly the same way as the last two protocols. This<br />

protocol is intended for methods which cause a ch<strong>an</strong>ge in the state of the object due to some calculation<br />

or operation. This protocol will be used to define the birthday method (see Figure 8.4).<br />

Figure 8.4: Defining the birthday message<br />

This last method uses the other methods in order to ch<strong>an</strong>ge the current value of the inst<strong>an</strong>ce variable<br />

age <strong><strong>an</strong>d</strong> to print a me<strong>an</strong>ingful message to the user.<br />

79

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

Saved successfully!

Ooh no, something went wrong!