CSE 341 -- Smalltalk Class Methods

In the system browser there are a pair of buttons "instance" and "class". Normally "instance" is depressed. This means that you are examining methods that define how instances of the class respond to messages. For example, for the Stack class we had methods such as push: and pop, which specify the response to messages that you can send to a stack instance.

You can also browse and define class methods -- to do this push the "class" button instead.

One common use of class methods is for constants that are associated with the class as a whole, rather than any particular instance. For example:

Float pi
Float e
Color blue
Another use is to create and initialize instances. Our previous version of Stack allowed us to create instances that weren't initialized -- we had to remember to send the newly created instance the message setsize: to initialize it.

We can avoid this by defining a class method new: for Stack, which creates a new instance and initializes it. The parameter is the initial size of the stack. While we're at it, we can also define new (overriding the standard new method) to create a stack with a default size.

new: size
   "create a new stack, initialize it, and return it.  We're going to 
    override new, so use the inherited version (with 'super new')."
     | s |
   s := super new.
   s setsize: size.
   ^s

new
   ^self new: 10
A more concise but equivalent definition of new: is
new: size
   ^super new setsize: size
(This would be more typical Smalltalk style -- I wrote out the long version just to make it clearer what is going on.)