Skip to main content
ICT
Lesson A2 - Object Oriented Programming
 
Main   Previous Next
 

C. Object Declaration, Creation, and Message Sending page 5 of 10

  1. Every object in a program must be declared. An object declaration designates the name of an object and the class to which the object belongs. Its syntax is:

    class_name object_name

    • class_name is the name of the class to which these objects belong.
    • object_name is a sequence of object names separated by commas.

In the case of the DrawSquare example, the myPencil object is declared as

DrawingTool myPencil;

other examples:

Account checking;
Customer bob, betty, bill;

The first declaration declares an Account object named checking, and the second declares three Customer objects.

  1. No objects are actually created by the declaration. An object declaration simply declares the name (identifier) that we use to refer to an object. Calling a constructor using the new operator creates an object. The syntax for creating an object is:

    object_name = new class_name ( arguments ) ;

    • object_name is the name of the declared object.
    • class_name is the name of the class to which the object belongs.
    • arguments is a sequence of zero or more values passed to the constructor.

    In the DrawSquare example, the paper object is created (instantiated) with the statement

  2. myPaper = new SketchPad(300, 300);

  3. After the object is created, we can start sending messages to it. The syntax for sending a message to an object is

    object_name.method_name( arguments );

    • object_name is the name of the declared object.
    • method_name is the name of a method of the object.
    • arguments is a sequence of zero or more values passed to the method.

In the DrawSquare example, the myPencil object is sent a sequence of messages; forward with an argument of 100, and turnLeft with an argument of 90.

    myPencil.forward(100);
    myPencil.turnLeft(90);

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.