Navigation:  Tutorials > Beginners Guide to Smalltalk > Classes and Methods >

Accessor Methods

Previous pageReturn to chapter overviewNext page

Since instance variables are not available to clients (users) of an object we needed to provide some means by which their data can be accessed when it is appropriate. We do this by adding methods to the class that are used to get and set the values of the instance variables. Such methods are generally known as accessor methods. Take a look at the following methods in the Point class:


       "Answer the receiver's x coordinate"




x: aNumber

       "Set the receiver's x coordinate"

       x := aNumber


These two methods are used to get and set the value of the receiver's x instance variable. You can also use accessor methods that set multiple instance variables at once or possibly calculate the value of an aspect of the object based on its instance variable contents. For example, take the following two methods:

x: xCoord y: yCoord

       "Private - Set the x and y coordinates of the receiver.

       Primarily intended for instance creation. Answer the receiver."


       x := xCoord.

       y := yCoord




       "Answer the receiver's radius (magnitude) in a polar coordinate



       ^(self dotProduct: self) sqrt