ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Inheritance | 27

In addition to invoking themakeSound( )method, theDogandCatinstances invoke their


own methods,bark( ) andmeow( ). Also, when you test the application, you will see:


QuadPets is instantiated

That output is caused by the line:


trace(“QuadPets is instantiated”);

placed in the constructor function of theQuadPetsclass. It fires whenever an instance


of the class is invoked. So in addition to having the capacity to use methods from the


superclass, subclasses inherit any actions in the constructor function of the superclass.


Open a Flash document, and typeTestPetsin the Document class window. When


you test it, you should see the following in the Output window:


QuadPets is instantiated
Superclass:Pet Sound
Dog class: Bow wow
QuadPets is instantiated
Superclass:Pet Sound
Cat class: Meow

Looking at the output, both the dog and cat instances display two superclass mes-


sages (QuadPets is instantiated,Superclass:Pet Sound) and one message unique to


the respective subclasses (Dog class: Bow wow,Cat class: Meow.) These examples


show how inheritance works, but in practical applications, and in design patterns,


inheritance is planned so that they cut down on redundancy and help build a pro-


gram to achieve an overall goal.


Example 1-16. TestPets.as


package
{
import flash.display.Sprite;


public class TestPets extends Sprite
{
public function TestPets( ):void
{
var dog:Dog=new Dog( );
dog.makeSound( );
dog.bark( );
var cat:Cat=new Cat( );
cat.makeSound( );
cat.meow( );
}
}
}

Free download pdf