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.
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
myPaper = new SketchPad(300, 300);
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.
myPencil.forward(100);
myPencil.turnLeft(90);