An Example of a Smalltalk Class

Introduction

This is a trivial example of the construction of a class in Smalltalk. The class Vegetable will only have a few functions, but this example will illustrate:

Creating a New Class

First select Browse Classes from the file menu. This will cause the program to display the Class Browser. Then follow these steps.

Select New Class from the Classes menu.
Type the name of your class in the appropriate location in the new class dialog.
Enter Instance variables in space following instanceVariableNames:
From this point on, any change should be followed by a call to update from the class menu.

Creating Instance Methods

Instance methods are methods used to update objects that are members of a given class. These objects are called instances of that class. The following steps are followed to create an instance method.

Select New Method from the Methods menu
The editing area will now show a template of what a method should look like.
Enter your method (this retrieves the number of calories of fat in a veggi). Update your class.
Enter a second function that sets the number of calories and prints some results.

Using Class Methods

Once again make sure you have updated your class. Next create a workspace then follow these steps.

Enter the text shown in this window and select doit from the right button menu
The results are displayed in the transcript.

Class Methods and How They Differ From Instance Methods.

Instance methods are messages sent to instances of a Class. These methods can only be sent to objects that have been created. One of the problems with this is when you are creating a new object, you don't have an object to send a message to, so it would seem that it is impossible to create an object with a method associated with the class of the object. Since only the class knows the structure of objects that belong to it, it should be the place where creation functions are defined. Class functions allow you to associate such constructing functions with the class, without requiring members of the class to call on them. Here we will create a vegetable with 25 fat calories without using any of the instance methods directly.

Creating Class Method

When creating a class method, you must first select the class radio button from the top of the browser (see screen dump below). Once you have done this proceed as if you were creating an instance method. One difference is that your class methods must return an instance, so allocating an instance is part of the process. Also note that class variables cannot reference instance member variables, so the functions used for altering these values are used to create this new instance.

To call a class method, remember that the Class receives the message and so no variable is needed.

Complete Class Definition

To run this class yourself download the class file and use install from the file menu in Smalltalk to install the class.