What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

What is Inheritance in Flash

About inheritance

About writing subclasses in Flash

About writing a subclass

Example: Extending the Widget class

Overriding methods and properties

Using polymorphism in an application

About inheritance

TOP

In Classes, you saw how you could create a class file to create your own custom data types. Learning how to create custom class files shows you how to move code off the timeline and into external files. Moving code into external files makes it easier to edit your code. Now that you're familiar with the basics of creating your own custom classes, you learn about an object-oriented programming (OOP) technique called subclassing or extending a class, which lets you create new classes based on an existing class.

One of the benefits of OOP is that you can create subclasses of a class. The subclass inherits all the properties and methods of a superclass. For example, if you extend (or subclass) the MovieClip class, you are creating a custom class that extends the MovieClip class. Your subclass inherits all of the properties and methods of the MovieClip class. Or you might create a set of classes that extends from a custom superclass. For example, the Lettuce class might extend from the Vegetable superclass.

Your subclass typically defines additional methods and properties that you can use in your application, hence it extends the superclass. Subclasses can also override (provide their own definitions for) methods inherited from a superclass. If a subclass overrides a method inherited from its superclass, you can no longer access the superclass's definition within the subclass. The only exception to the above rule is that, if you are within the subclass's constructor function, you call the superclass's constructor using the super statement. For more information on overriding, see Overriding methods and properties.

For example, you might create a Mammal class that defines certain properties and behaviors that are common to all mammals. You could then create a Cat subclass that extends the Mammal class. Using subclasses lets you reuse code so that instead of re-creating all the code common to both classes you could simply extend an existing class. Another subclass, the Siamese class, could extend the Cat class, and so on. In a complex application, determining how to structure the hierarchy of your classes is a large part of the design process.

Inheritance and subclassing are very useful in larger applications, because they let you create a series of related classes that can share functionality. For example, you could create an Employee class that defines the basic methods and properties of a typical employee within a company. You could then create a new class called Contractor that extends the Employee class and inherits all of its methods and properties. The Contractor class could add its own specific methods and properties, or it could override methods and properties that are defined in the Employee superclass. You could then create a new class called Manager, which also extends the Employee class and defines additional methods and properties such as hire(), fire(), raise(), and promote(). You could even extend a subclass, such as Manager, and create a new class called Director, which again adds new methods or overrides existing methods.

Each time that you extend an existing class, the new class inherits all the current methods and properties of the subclass. If each class wasn't related, you'd have to rewrite each method and property in each separate class file, even if the functionality was the same in the fellow classes. You would have to spend a lot more time not only coding, but also debugging your application and maintaining a project if similar logic changed in multiple files.

 

About writing subclasses in Flash

TOP

In object-oriented programming, a subclass can inherit the properties and methods of another class, called the superclass. You can extend your own custom classes as well as many of the core and Flash Player ActionScript classes. You cannot extend the TextField class or static classes, such as the Math, Key, and Mouse classes.

To create this kind of relationship between two classes, you use the class statement's extends clause. To specify a superclass, you use the following syntax:

class SubClass extends SuperClass {}

The class you specify in SubClass inherits all the properties and methods defined in SuperClass.

For example, you might create a Mammal class that defines properties and methods common to all mammals. To create a variation of the Mammal class, such as a Marsupial class, you would extend the Mammal class--that is, create a subclass of the Mammal class, as follows:

class Marsupial extends Mammal {}

The subclass inherits all the properties and methods of the superclass, including any properties or methods that you have declared to be private using the private keyword.

 

About writing a subclass

TOP

The following code defines the custom class JukeBox, which extends the Sound class. It defines an array called song_arr and a method called playSong(), which plays a song and invokes the loadSound() method that it inherits from the Sound class.

class JukeBox extends Sound {

public var song_arr:Array = new Array("beethoven.mp3", "bach.mp3", "mozart.mp3");

public function playSong(songID:Number):Void {

super.loadSound(song_arr[songID], true);

}

}

If you don't place a call to super() in the constructor function of a subclass, the compiler automatically generates a call to the constructor of its immediate superclass with no parameters as the first statement of the function. If the superclass doesn't have a constructor, the compiler creates an empty constructor function and then generates a call to it from the subclass. However, if the superclass takes parameters in its definition, you must create a constructor in the subclass and call the superclass with the required parameters.

Multiple inheritance, or inheriting from more than one class, is not allowed in ActionScript 2.0. However, classes can effectively inherit from multiple classes if you use individual extends statements, as shown in the following example:

// not allowed

class C extends A, B {} // **Error: A class may not extend more than one class.

// allowed

class B extends A {}

class C extends B {}

 

Example: Extending the Widget class

TOP

Class members propagate to subclasses of the superclass that defines those members. The next example demonstrates how you could create a Widget class, which you extend (subclass) by writing a class named SubWidget.

To create the Widget class and SubWidget subclass:

  1. Create a new ActionScript file and save it as Widget.as.

  2. Add the following code to the new document:

    class Widget {

    public static var widgetCount:Number = 0;

    public function Widget() {

    Widget.widgetCount++;

    }

    }

  3. Save your changes to the ActionScript file.

  4. Create a new ActionScript file and save it as SubWidget.as in the same directory as the Widget class.

  5. In SubWidget.as, type the following code into the Script window:

    class SubWidget extends Widget {

    public function SubWidget() {

    trace("Creating subwidget #" + Widget.widgetCount);

    }

    }

  6. Save your changes to SubWidget.as.

  7. Create a new FLA file, and save it as subWidgetTest.fla in the same directory as the previous ActionScript class files.

  8. In the subWidgetTest.fla file, type the following code into Frame 1 of the main Timeline:

    var sw1:SubWidget = new SubWidget();

    var sw2:SubWidget = new SubWidget();

    trace("Widget.widgetCount = " + Widget.widgetCount);

    trace("SubWidget.widgetCount = " + SubWidget.widgetCount);

    The previous code creates two instances of the SubWidget class: sw1 and sw2. Each call to the SubWidget constructor traces the current value of the static Widget.widgetCount property.

  9. Because the SubWidget class is a subclass of the Widget class, you can access the widgetCount property through the SubWidget class, and the compiler rewrites the reference (in the bytecode, not in your ActionScript file) as Widget.widgetCount. If you try to access the static widgetCount property off of instances of the Widget or SubWidget class, like sw1 or sw2, the compiler throws an error.

  10. Save your changes to the document.

  11. Select Control > Test Movie to test the Flash document.

    The Output panel displays the following output:

    Creating subwidget #1

    Creating subwidget #2

    Widget.widgetCount = 2

    SubWidget.widgetCount = 2

    You see this output because even though the Widget class's constructor is never explicitly called, the SubWidget class's constructor calls it for you. This causes the Widget class's constructor to increment the Widget class's static widgetCount variable.

    The ActionScript 2.0 compiler can resolve static member references within class definitions.

    If you don't specify the class name for the Widget.widgetCount property but instead refer only to widgetCount, the ActionScript 2.0 compiler resolves the reference to Widget.widgetCount and correctly exports that property. Similarly, if you refer to the property as SubWidget.widgetCount, the compiler rewrites the reference (in the bytecode, not in your ActionScript file) as Widget.widgetCount because SubWidget is a subclass of the Widget class.

    CAUTION : If you try to access the static widgetCount variable from the Widget class using the sw1 or sw2 instances, Flash generates an error telling you that static members can be accessed only directly through classes.

 

Overriding methods and properties

TOP

When a subclass extends a superclass, the subclass inherits all of the superclass's methods and properties. One of the advantages of working with classes and extending classes is that it allows you not only to provide new functionality to an existing class but also to modify existing functionality. For example, consider the Widget class that you created in Example: Extending the Widget class. You could create a new method in your superclass (Widget) and then either override the method in your subclass (SubWidget) or just use the inherited method from the Widget class. The following example shows how you can override existing methods in your classes.

To override methods in a subclass:

  1. Create a new ActionScript document and save it as Widget.as.

  2. In Widget.as, type the following ActionScript code into the Script window.

    Note: If you created the Widget class in an earlier example, modify the existing code by adding the doSomething() method, as follows:

    class Widget {

    public static var widgetCount:Number = 0;

    public function Widget() {

    Widget.widgetCount++;

    }

    public function doSomething():Void {

    trace("Widget::doSomething()");

    }

    }

  3. Save your changes to the ActionScript document.

    The Widget class now defines a constructor and a public method called doSomething().

  4. Create a new ActionScript file named SubWidget.as and save it in the same directory as Widget.as.

    NOTE : If you created the SubWidget class in Example: Extending the Widget class, you can use this file instead.

  5. In SubWidget.as, type the following ActionScript code into the Script window:

    class SubWidget extends Widget {

    public function SubWidget() {

    trace("Creating subwidget # " + Widget.widgetCount);

    doSomething();

    }

    }

  6. Save your changes to SubWidget.as.

    Notice that the SubWidget class's constructor calls the doSomething() method that you defined in the superclass.

  7. Create a new Flash document and save it as subWidgetTest.fla in the same directory as the ActionScript documents.

  8. In subWidgetTest.fla, type the following ActionScript into Frame 1 of the main Timeline:

    var sw1:SubWidget = new SubWidget();

    var sw2:SubWidget = new SubWidget();

  9. Save your changes to the Flash document.

  10. Select Control > Test Movie to test the Flash document. You see the following output in the Output panel:

    Creating subwidget # 1

    Widget::doSomething()

    Creating subwidget # 2

    Widget::doSomething()

    This output shows that the SubWidget class's constructor calls the constructor of its superclass (Widget), which increments the static widgetCount property. The SubWidget's constructor traces the superclass's static property and calls the doSomething() method, which inherits from the superclass.

  11. Open the SubWidget class and add a new method named doSomething(). Modify your class so that it matches the following code (add the code that's in boldface):

    class SubWidget extends Widget {

    public function SubWidget() {

    trace("Creating subwidget # " + Widget.widgetCount);

    doSomething();

    }

    public function doSomething():Void {

    trace("SubWidget::doSomething()");

    }

    }

  12. Save your changes to the class file, and then open subwidgetTest.fla again.

  13. Select Control > Test Movie to test the file. You see the following output in the Output panel:

    Creating subwidget # 1

    SubWidget::doSomething()

    Creating subwidget # 2

    SubWidget::doSomething()

    The previous output shows that the doSomething() method in the SubWidget class's constructor is calling the doSomething() method in the current class instead of the superclass.
    Open the SubWidget class again, and modify the SubWidget class's constructor to call the superclass's doSomething() method (add the code that's in boldface):

    public function SubWidget() {

    trace("Creating subwidget # " + Widget.widgetCount);

    super.doSomething();

    }

    As demonstrated, you can add the super keyword to call the superclass's doSomething() method instead of the doSomething() method in the current class. For additional information on super, see the super entry in the ActionScript 2.0 Language Reference.

  14. Save the SubWidget class file with the modified constructor and select Control > Test Movie to republish the Flash document.

    The Output panel displays the contents of the Widget class's doSomething() method.

 

Using polymorphism in an application

TOP

Object-oriented programming lets you express differences between individual classes using a technique called polymorphism, by which classes can override methods of their superclasses and define specialized implementations of those methods.

For example, you might start with a class called Mammal that has play() and sleep() methods. You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The subclasses override the play() method from the Mammal class to reflect the habits of those particular kinds of animals. Monkey implements the play() method to swing from trees; Cat implements the play() method to pounce at a ball of yarn; Dog implements the play() method to fetch a ball. Because the sleep() functionality is similar among the animals, you would use the superclass implementation. The following procedure demonstrates this example in Flash.

To use polymorphism in an application:

  1. Create a new ActionScript document and save it as Mammal.as.

    This document is the base class for a few different animal classes that you create in upcoming steps.

  2. In Mammal.as, type the following ActionScript code into the Script window:

    class Mammal {

    private var _gender:String;

    private var _name:String = "Mammal";

    // constructor

    public function Mammal(gender:String) {

    this._gender = gender;

    }

    public function toString():String {

    return "[object " + speciesName + "]";

    }

    public function play():String {

    return "Chase another of my kind.";

    }

    public function sleep():String {

    return "Close eyes.";

    }

    public function get gender():String {

    return this._gender;

    }

    public function get speciesName():String {

    return this._name;

    }

    public function set speciesName(value:String):Void {

    this._name = value;

    }

    }

    The previous class defines two private variables, _gender and _name, which are used to store the animal's gender and mammal type. Next, the Mammal constructor is defined. The constructor takes a single parameter, gender, which it uses to set the private _gender variable defined earlier. Three additional public methods are also specified: toString(), play(), and sleep(), each of which returns string objects. The final three methods are getter and setter methods for the mammal's _gender and _name properties.

  3. Save the ActionScript document.

    This class serves as the superclass for the Cat, Dog, and Monkey classes, which you create shortly. You can use the toString() method of the Mammal class to display a string representation of any Mammal instance (or any instance that extended the Mammal class).

  4. Create a new ActionScript file and save it as Cat.as in the same directory as the Mammal.as class file you created in step 1.

  5. In Cat.as, type the following ActionScript code into the Script window:

    class Cat extends Mammal {

    // constructor

    public function Cat(gender:String) {

    super(gender);

    speciesName = "Cat";

    }

    public function play():String {

    return "Pounce a ball of yarn.";

    }

    }

    Notice that you are overriding the play() method in the Mammal superclass. The Cat class defines only two methods, a constructor and a play() method. Since the Cat class extends the Mammal class, the Mammal classes's methods and properties are inherited by the Cat class. For more information on overriding, see Overriding methods and properties.

  6. Save your changes to the ActionScript document.

  7. Create a new ActionScript document and save it as Dog.as in the same directory as the two previous class files.

    In Dog.as, type the following ActionScript code into the Script window:

    class Dog extends Mammal {

    // constructor

    public function Dog(gender:String) {

    super(gender);

    speciesName = "Dog";

    }

    public function play():String {

    return "Fetch a stick.";

    }

    }

    Notice that the Dog class is very similar in structure to the Cat class, except that a few of the values have changed. Again, the Dog class extends the Mammal class and inherits all its methods and properties. The Dog constructor takes a single property, gender, which it passes to the Dog class's parent class, Mammal. The speciesName variable is also overridden and set to the string Dog. The play() method is also overridden from the parent class.

  8. Save your changes to the ActionScript document.

  9. Create another ActionScript document in the same directory as your other files, and save it as Monkey.as.

    In Monkey.as, type the following ActionScript code into the Script window:

    class Monkey extends Mammal {

    // constructor

    public function Monkey(gender:String) {

    super(gender);

    speciesName = "Monkey";

    }

    public function play():String {

    return "Swing from a tree.";

    }

    }

    Similar to the previous two classes, Cat and Dog, the Monkey class extends the Mammal class. The Monkey class's constructor calls the constructor for the Mammal class, passing the gender to the Mammal's constructor, as well as setting speciesName to the string Monkey. The Monkey class also overrides the behavior of the play() method.

  10. Save your changes to the ActionScript document.

  11. Now that you've created three subclasses of the Mammal class, create a new Flash document called mammalTest.fla.

  12. In mammalTest.fla, type the following ActionScript code into Frame 1 of the main Timeline:

  13. var mammals_arr:Array = new Array();

    this.createTextField("info_txt", 10, 10, 10, 450, 80);

    info_txt.html = true;

    info_txt.multiline = true;

    info_txt.border = true;

    info_txt.wordWrap = true;

    createMammals()

    createReport()

    function createMammals():Void {

    mammals_arr.push(new Dog("Female"));

    mammals_arr.push(new Cat("Male"));

    mammals_arr.push(new Monkey("Female"));

    mammals_arr.push(new Mammal("Male"));

    }

    function createReport():Void {

    var i:Number;

    var len:Number = mammals_arr.length;

    // Display Mammal info in 4 columns of HTML text using tab stops.

    info_txt.htmlText = "<textformat tabstops='[110, 200, 300]'>";

    info_txt.htmlText += "<b>Mammal\tGender\tSleep\tPlay</b>";

    for (i = 0; i < len; i++) {

    info_txt.htmlText += "<p>" + mammals_arr[i].speciesName

    + "\t" + mammals_arr[i].gender

    + "\t" + mammals_arr[i].sleep()

    + "\t" + mammals_arr[i].play() + "</p>";

    // The trace statement calls the Mammal.toString() method.

    trace(mammals_arr[i]);

    }

    info_txt.htmlText += "</textformat>";

    }

    The mammalTest.fla code is a bit more complex than the previous classes. First it imports the three animal classes.

  14. Save the Flash document, and then select Control > Test Movie to test the document.

    You see the Mammal information displayed in a text field on the Stage, and the following text in the Output panel:

    [object Dog]

    [object Cat]

    [object Monkey]

    [object Mammal]

 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash