Quick Review of Objects

Remember back in Chapter 5, I defined an object as an active data type that knows stuff and can do stuff. More precisely, an object consists of

1. A collection of related information.

2. A set of operations to manipulate that information.

The information is stored inside the object in instance variables. The operations, called methods, are functions that "live" inside the object. Collectively, the instance variables and methods are called the attributes of an object.

To take a now familiar example, a Circle object will have instance variables such as center, which remembers the center point of the circle, and radius, which stores the length of the circle's radius. The methods of the circle will need this data to perform actions. The draw method examines the center and radius to decide which pixels in a window should be colored. The move method will change the value of center to reflect the new position of the circle.

Recall that every object is said to be an instance of some class. The class of the object determines what attributes the object will have. Basically a class is a description of what its instances will know and do. New objects are created from a class by invoking a constructor. You can think of the class itself as a sort of factory for stamping out new instances.

Consider making a new circle object:

Circle, the name of the class, is used to invoke the constructor. This statement creates a new Circle instance and stores a reference to it in the variable myCircle. The parameters to the constructor are used to initialize some of the instance variables (namely center and radius) inside of myCircle. Once the instance has been created, it is manipulated by calling on its methods:

myCircle.draw(win) myCircle.move(dx, dy)

Was this article helpful?

0 0

Post a comment