O'Reilly logo

Learning ActionScript 3.0 by Zevan Rosser, Rich Shupe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Composition

Although inheritance is a very common practice in object-oriented programming, it is not the only way for classes to work together. Composition, sometimes referred to as aggregation, is also appropriate in many circumstances. Composition says that an object can be composed of other objects, rather than descend from other objects. The best way to describe composition is by example, using a handy rule of thumb that asks "is a" or "has a."

Consider how to add tires to the vehicle example. You might be able to use inheritance ("is a"), but composition ("has a") might be better. A car "is a" vehicle, meaning inheritance will work well, but tires don't fit the "is a" vehicle or car or truck model. However, a car (and truck) "has a" set of tires, making this model suitable for composition. Composition makes it easier to switch out items of which a class is composed. If a car is extended from a vehicle, then you can't change that any more than you can change your blood relatives, parent, or child. However, if a car is composed of things, including tires, you can easily switch one set of tires for another.

Vehicle class

Let's start the composition example by adding a _tires property to the Vehicle class, as seen in line 13 of the class. This makes the property available to the Car and Truck classes.

1 //Vehicle.as 2 package { 3 4 import flash.display.MovieClip; 5 import flash.events.Event; 6 7 public class Vehicle extends MovieClip { 8 9 public var _gasMileage:Number; 10 public var ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required