Navigation:  Tutorials > Beginners Guide to Smalltalk > Programming in Smalltalk >

Instance creation methods

Previous pageReturn to chapter overviewNext page

By default, all classes respond to a #new message and answer an instance of the class. We used this fact in our previous test. We didn't have to write the #new method ourselves since all classes inherit this via their superclass chain.

Tip: You might expect to find this method in the Object class. However, it isn't there, but rather it's in class Class. Why not use the browser to take a look?

However, using #new to create an instance of Animal isn't really ideal since, as we've seen, we end up with an animal that has a nil name. It would be much better if we could ensure that as each instance is created it is properly initialized with a valid String name. We can do this by adding an instance creation method that takes as its parameter the name of the animal to be created. Such a method is not applicable to an instance of Animal but rather to the class itself. For this reason it is called a class method (as opposed to the instance methods we have created so far).

To create a class method you must first select the Class mode button in the browser.


The browser will then switch to displaying the class methods of the current class rather than its instance methods. Now add the following method to the class side:

name: aStringName

       "Answer an instance of the receiver with aStringName"

       ^self new name: aStringName

 

As you can see, this creates a new instance of Animal and then sends it a #name: message to initialize its name.

Tip: Now it might become apparent why we marked the #name: method on the instance side of Animal as being private. The intention is that this method will only be called from the class method of the same name. We don't expect that an Animal instance, once it has been created, will ever have its name changed so we indicate this by suggesting the method is private and therefore it should not be called explicitly.