Skip to main content
Lesson 1 - Introduction to Object Oriented Programming
Lesson MenuPreviousNext
  
Messages and Methods page 4 of 8

  1. In writing object-oriented programs we first define classes, and while the program is running, we create objects from these classes to accomplish tasks. A task can range from drawing in a paint program, to adding numbers, to depositing money in a bank account. To instruct a class or an object to perform a task, we send a message to it.

  2. You can send a message only to the classes and objects that understand the message. For an object to process the message it receives, it must possess a matching method, which is a sequence of instructions an object follows to perform a task.

  3. For example, consider what kind of operations you can carry out with a pencil. You can

    • draw a line in the forward direction
    • change the drawing direction by turning left
    • get the current drawing color

  4. Suppose you have an object myPencil of type DrawingTool. You could represent the behaviors of the DrawingTool class with the methods

    • forward
    • turnLeft
    • getColor

  5. To draw a line of a specified length, we send the message forward along with the distance to move the pencil. A value we pass to an object is called an argument of a message. A diagram of sending a message is shown below in Figure 1.3.

    Figure 1.3 - Sending a forward message to a DrawingTool object

  6. The diagram shown in Figure 1.3 illustrates a situation in which an object carries out a request (it draws a line 100 units long) but does not respond to the message sender. In many situations, we need an object to respond by returning a value to the message sender. For example, suppose we want to know the current color that is being used for drawing. We can use the getColor message to return the value. A method that returns a value to a message sender is illustrated in Figure 1.4 below.

    Figure 1.4 - The result of getColor is returned to the sender of the message


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.