The relationship that classes have can be generally grouped into "is a" and "has a" categories. When a class has an "is a" relationship with another class, we call that inheritance. (Inheritance is discussed in Lesson 6.) Inheritance is appropriate in many cases. For example, to use the ever-popular car example, a car is a vehicle. Therefore, if a Vehicle class exists, it would be appropriate for a Car class to subclass it. However, inheritance is frequently used when inappropriate. To continue with the car example, a car has a wheel. It would be an obvious mistake to say that a car is a wheel. Yet a frequent programming mistake is to try to define inheritance relationships when they are not appropriate. When a class has an instance of another class, we call that composition. Therefore, in a composition relationship, a Car class has a Wheel (or four) property. As you can likely see, inheritance and composition are not necessarily at odds with one another. For example, a Car class can have an inheritance relationship with a Vehicle class and a composition relationship with the Wheel class. Some composition relationships are obvious. Some composition relationships are established because they are necessary given the way that Flash and ActionScript work. One such example is necessary because of the way in which the MovieClip class works. There are many scenarios in which you want to write a class that would seem to have an "is a" inheritance relationship with MovieClip. However, when you want to subclass MovieClip, you have to associate the class with a symbol in the library. Then you cannot construct an instance of the class with the constructor. Instead, you have to use attachMovie() to add an instance of the symbol. In some cases, that is okay, but in some cases that presents some obstacles to good workflow and design. Instead, it can be beneficial to write a class that uses composition rather than inheritance. In such cases the class has a MovieClip instance property. In this task, you'll see an example of that. There are many cases in which you'll potentially want to draw a rectangle within an empty movie clip. This scenario presents a perfect case for using composition. If you wanted to use inheritance you'd have to have an empty movie clip symbol with which to associate the class. You'd then have to add instances of the class with attachMovie(). A much more intuitive API would be once in which you can simply call the class constructor. Composition makes that possible. In this task, you'll write a Rectangle class that draws a rectangle in a new movie clip.
|