Chapter 2: Objects and Messages


Return to [ Table of Contents] [ Main Page] [ Previous Chapter] [ Next Chapter]

Sending Messages to Objects

As mentioned before, all Smalltalk processing is accomplished by sending messages to objects. An initial problem solving approach in Smalltalk is to try to reuse the existing objects and messages. The Smalltalk programmer works to develop an object-message sequence that will provide the desired solution. (See also "Object-Oriented Problem Solving Approach".)

Objects are instances of a particular class. The messages that an object can respond to is defined in the protocol of its class. How messages are executed or implemented is defined in the class methods. Methods give the implementation details for the messages and represent a class behavior.

Before going any further, let's take a look on how objects and messages are named.


Object and Message Naming

In this tutorial, all class names begin with a capital letter such as "Student". Message names begin with a lower case letter and can have any combination of letters and numbers without embedded blank spaces. When a message name contains more than one word, the extra words start with a capital letter. A valid message name would be "aMessage" or "myAddress."

A message such as "give me your name" could be "giveMeYourName". This however, is too difficult to work with. It would be easier to shorten it to just "name".

A message that passes information or parameters, such as "set the name to this name", is handled similarly, except that the method name must end with a colon (:). So, The message name becomes "name:". These types of messages are called keyword messages. Messages that have no information to pass are unary messages.

A message can contain multiple arguments. There has to be a keyword for every argument in the message. For example, it is possible to set both the name and the address of a student with one message. This requires a message name with two keywords such as "name:address:".

There are three types of messages: unary, binary and keyword .

Unary Messages

An Unary message is similar to a single-parameter function call. This type of message consists of a message name and an operand. The objects are put before the message name. The following are examples of unary message:


  x sin                   "return the result of sin(x)"       

  Date tomorrow           "answer a new instance of class Date"

  5 factorial             "return the factorial of 5"

  `hi' outputToPrinter    "Send the string `hi' to the printer"
      

In these examples `x', `Date', `5', and `hi' are the objects and `sin', `tomorror', `factorial', and `outputToPrinter' are the message names.

Binary Messages

Binary messages are used to specify arithmetic, comparison, and logical operations. A binary message can be either one or two characters long and can contain any combination of the following special characters:


          + / \ * ~ < > = @ % | & ? ! ,

The following are examples of Smalltalk expressions using binary messages:


      a + b            "returns the result of sum a and b"

      a | b            "returns the result of "ORing" a with b"

      a >= b           "compares to see if a is greater than or 
                        equal to b and returns either true or false" 

The first example can also read as "the message `+' is sent to the object `a' with a parameter `b'."

Keyword Messages

A Keyword message is equalvalent to a procedure call with two or more parameters. Look at the following example, the name of the object to which the message is sent is written first, then the name of the message (or method name), and follow by the parameter to be passed.


          AnObject aMessage: parameter

The colon is a required part of the message name.

When there is more than one parameter, a message name must appear for each parameter.

For example:


          AnObject aName1: parameter1 aName2: parameter2 

Here:

Examples of keyword messages:


     Array new: 20             "The message new: is sent to the object
                                Array with parameter 20"

     TheDate month: currentMonth year: currentYear   
                               "Set the private data for object TheDate 
                                to month = currentMonth and year = currentYear"

     Student name: `Steve' address: `Raleigh,        
                               "Set the appropriate variables in the 
                                Student object according to the parameters"


Message Format

In general, a Smalltalk expression consists of the name of the object that receives the message, followed by the message name.

For example:

 
      AnObject aMessage

For messages that need to pass arguments to the receiving object, such as a keyword message, the receving object's name is followed by the message name and its argument. The arguments are separated by a blank space.


      AnObject aNumber: 1 aName: `John'

Object Identifiers

When an object is created, Smalltalk assigns an identifier to it. Each object has its own unique identifier that has meaning only to the Smalltalk system.

A variable in Smalltalk contains the identifier of the object, not the object itself. In other words, a variable points to an object. When the receiver of a message is a variable, Smalltalk uses the contents of the variable to identify the object. For example, assume that there is a global variable called MyStudent that points to a Student object. The global variable, MyStudent can now be the receiver of the following messages:


         MyStudent name: `Steve'

         MyStudent name

Creating New Instances

To create a new instance for a class, the new message is sent to the class.

For example:

Student new

Every class automatically supports the new message. The new message then returns a pointer to the new instance.

In the following example, the global variable MyStudent points to a new Student object:


         MyStudent := Customer new

In Smalltalk, the := expression is the syntax for the assignment function. The variable on the left points to the result of the expression on the right.

Once the statement above has been executed, messages can be sent to MyStudent, which points to an instantiation of a Student object.

For example:


         MyStudent name: `Steve'

         MyStudent name


Concept of self

Consider the following statement:


         MyStudent name: `Steve' address: `Raleigh, NC'.

The statement sends the message name:address: to the Student object pointed to by the variable MyStudent. Rather than duplicating the code that already exists in the name: and address: methods, the method name:address: is implemented to have name: and address: perform the task. Since name: and address: are methods of the same object as name:address:, there must be a way for a method to refer to the object in which it exists.

That is the purpose of self. A method can access other methods in its own object by specifying self as the receiver of the message.

Let's look at the code for all three of these methods:


         name: aName
               name := aName

         address: anAddress
               address := anAddress

         name: aName address: anAddress
               self name: aName.
               self address: anAddress

The use of self causes Smalltalk to send the name and address messages to the current instance of Student, the same instance that received the name:address: message.

In the example, the methods name: and address: defined their temporary variables with the same identities that are found in name:address:. There is no relationship between these names and they do not have to be the same. The scope of a method's temporary variables are local only to that method. For example, the name: mehtod could also look like this:


          name: studentName
              name := studentName

The name:address: method could choose to directly set the variables instead of using the lower-level methods of name: and address:. This would appear as follows:


          name: aName address: anAddress
              name := aName
              address := anAddress

It is better, however, to centralize the setting of a variable inside a single method. The same is true for getting the contents of a variable.


Order of Message Execution

The rules that Smalltalk use when deciding the order of exercuting messages can be summarize as the following:

  1. Smalltalk executes messages from left to right.
  2. The result of a message replaces that message in the statement.
  3. Smalltalk executes all expression that appear inside a pair of parenthesis first, with the left-most inner pair of nested parenthesis.
  4. Inside an expression, unary messages are executed first, followed by binary messages, followed by keyword messsage, in a left-to-right direction.
  5. Smalltalk executes all binary messages from left to right, regardless of what operations they perform. This means there is no special order of execution for arithmetic operations.
  6. An expression can include a variable name. Smalltalk replaces the variable name with the object to which it points.

Summary

We have discussed the following in this chapter:

  • All Smalltalk processing involves sending messages to objects. Class methods define the behavior of the class messages.

  • Class names begin with capital letters and message names begin with lowercase letters. The three types of messages are: unary, binary, and keyword.

  • A general Smalltalk expression consist of the name of the object that receives the message followed by the message name and its arguments.

  • An object can send a message to itself by specifying the name self as the receiving object.

  • Smalltalk has a series of execution-time rules for evaluating a Smalltalk statement. There are four important rules for evaluating code:
    1. All code is evaulated left to right.
    2. Expressions within parentheses are evaluated first, starting with the left-most inner parenthesis.
    3. The result of a message takes the place of that message in an expression.
    4. Unary messages are executed first, followed by binary messages , followed by keyword messages.

    Return to [
    Top of the page]
    Smalltalk Tutorial

    Go to Chapter 3: Smalltalk Statements

    Return to Chapter 1: Introduction to IBM Smalltalk Programming

    Return to Main Page