Home > Articles > Graphics & Web Design > Dreamweaver & Flash

  • Print
  • + Share This
This chapter is from the book

Object-Oriented and Procedural Programming

Those who know OOP already or who really don't want to be heavily involved in programming can skip this section. This section is important for readers who are new to object-oriented programming (OOP) and who want to optimize their scripts using ActionScript 2.0. To optimally work with ActionScript 2.0 and OOP, I recommend reading a book on OOP to fully understand the object-oriented approach to programming. An especially valuable book that deals with Flash MX 2004 and OOP is Jeff Tapper's Object-Oriented Programming with ActionScript 2.0 (New Riders, 2004, ISBN 0735713804).

To begin understanding OOP, you need to know a little about what the OOP approach replaces. Originally, programming took a procedural approach. The procedural approach executes a series of procedures sequentially. Chances are that if you've programmed extensively in ActionScript 1.0, many of your programs are procedural. For simple programming, the procedural approach works fine. However, as programmers began encountering larger programming tasks, they found that large projects involving multiple programmers were problematic, and they needed a new approach. ActionScript 1.0 had some relatively simple OOP structures, and many ActionScript programmers took full advantage of those structures. So for some, OOP in ActionScript 2.0 certainly is not a brand-new topic.

Real-World Modeling

Rather than dealing with procedures that could be accessed from anywhere in a program, OOP developed the idea that programming should better reflect the real world in the problem-solving work accomplished by the program elements. To reflect real-world models, OOP took the object as its central concept. Objects in the real world have characteristics and behaviors—nouns and verbs, as it were. For instance, you may know a person who has brown eyes and brown hair, is 6 feet tall, and likes to jog and eat Mexican food.

These are some of the characteristics of the person:

  • Brown eyes

  • Brown hair

  • Six feet tall

These are some of the behaviors of the person:

  • Jogging

  • Eating Mexican food

Obviously, people have more characteristics and behaviors than those listed, but most of the objects you deal with in Flash are made up of just a few characteristics and behaviors.

In the parlance of OOP, an object's characteristics are called properties and its behaviors are called methods. One way to think of properties is that they are something like a variable that can have different values. If one of the characteristics (properties) of an object is "hair color," you can have red, blonde, black, brown, or even blue, just as a variable called hairColor can have different hues. The methods of an object are something like functions in a program. They call for some kind of behavior. Imagine an object in a Flash movie that simulates jogging by rapidly increasing the pace of movements of the arm and leg parts. The object might include both walk and jog methods, and when the jog method is called, the object moves faster than if the walk method is called.

Classes and Objects

In ActionScript 2.0, you create a class typically saved in an AS file, and you use instances of that class in your scripts written in the Actions panel. Think of a class as a mold, and when you need to use the class, the mold pops out an object (an instance) with all the characteristics of the mold. So, if you have a "person" mold (class) with brunette hair who jogs, to bring that person to life, you create a new instance of the jogging brunette. The mold (class) itself simply describes what the objects it creates can do. The objects themselves are the instances created in the Actions panel. Depending on whether you're a purist, you can accept different definitions of classes and objects. The most common, and probably most useful, conception of classes and objects is one that treats an object as an instance of a class. A purist definition follows the reasoning that a class is an object from which other objects can be created, and although that conception is perfectly correct, treating objects as instances of a class helps differentiate between the creating term (class) and the term in use (object) in a program.

Project: Creating a Class in ActionScript 2.0

For those familiar with OOP from ActionScript 1.0, where prototype classes were created, you will find creating classes in ActionScript 2.0 both different and in most respects easier. You can still create a class using the prototype function, but otherwise all user classes are created in an external AS file. Likewise, extensions of built-in files are created in the same external kind of file. Only a single class or extension of a class can be created in a single file. However, a document can have as many files containing classes as you need in a program. The name of the AS file must be saved as the name of the class. The names of classes, as well as the AS files containing their definitions, begin with a capital letter. For example, if you define a class as Car, the name of the AS file would be Car.as so that it can be compiled correctly.

Creating a Class in an AS file

Use the Script window to write your class AS files. Open a new Script window by selecting File, New from the menu and then selecting ActionScript File from the General tab. You can write AS files in virtually any pure text editor, such as Microsoft Notepad, but the Script window provides both code hints and script formatting that make scripting much easier.

To help you understand how a class works in Flash MX Professional 2004, a simple example is in order. In this example, the class has a single property (a string for the name of a color) and a single method (a statement that outputs the values of the property). Follow these steps:

  1. Using the new Flash MX Professional 2004 Script window, save the following script with the name ColorShow.as:

  2. class ColorShow {
     var colorName:String;
     function ColorShow(someColor:String) {
     this.colorName = someColor;
     function outNow():String {
     return colorName;

    When you use a class in a program, you need to place the AS file with the class definition in the same folder as the FLA file. The class is compiled into the SWF file when published; therefore, the SWF file need not be in the same folder as the AS file.

    Creating a Path to a Class File

    If you have programs with several classes, you may find it more convenient to place all the classes in a subfolder. For longer-range planning, you may decide to place all your classes in a folder separate from all your Flash projects so that they can be used by any single project. Part of OOP includes reusability, and the ability to access classes anywhere on the developer's hard drive is a good feature where reusable code is concerned. To create a path to your class file, use the following steps:

    1. Create a class file and save it to your hard drive.

    2. Create your FLA file, save it, and then select File, Publish Settings from the menu bar.

    3. In the Publish Settings dialog box, select the Flash tab.

    4. Select ActionScript 2.0 in the ActionScript Version pop-up menu.

    5. Click the Settings button next to the ActionScript version to open the ActionScript Settings window. Click the plus (+) button beneath Classpath in the ActionScript Settings window.

    6. In the live text box beneath the plus (+) button, type the path to your class AS file. For example, if you're placing all your classes in a subfolder within the folder (named classes) containing your FLA file, type in classes/ for the class path. Figure 3.1 shows what you get.

    Figure 3.1Figure 3.1 You can create any path to your AS files that you want.

  3. Now that the class is written and you've decided on the default path, you can create a Flash document that uses the class. The following script, written in the Actions panel, creates an instance of the class named showOff:

  4. var showOff:ColorShow = new ColorShow("Green");
    display_txt.text = showOff.outNow();

    Because this script creates an instance of the class, showOff is the object (instance) in the object-oriented program. Moreover, using similar short scripts that use the class, you can re-create other objects to display any value you want.

  5. On the Stage, place a dynamic text field and give it the instance name display_txt. Now, whatever color name (or any other string for that matter) that you place in the ColorShow() argument appears in the output window.

Using this simple example, we can now look at the key features of OOP. Three key concepts make up the foundation of OOP:

  • Encapsulation

  • Inheritance

  • Polymorphism

Each will be described briefly, but you are encouraged to look at a more detailed work on OOP to fully understand their use and value.


In some office construction, rooms are added as modules. A big crane lifts a prebuilt room and sets it in place with the other rooms. This module is a self-contained entity, even though it's part of a larger structure. You can think of encapsulation in OOP as a self-contained module. It contains the data (properties) and functions (methods) to get something done, just as the different rooms in a module-built building have self-contained capsules used for different purposes. As such, classes in OOP are independent, but they can interact with other instances of the same and different classes in a program.

In our example, the property colorName is a string that is determined by the value placed in the class argument (someColor). To be fully encapsulated, the instance cannot be exposed, so a method, outNow, is included to provide the value of the property. With both the property and method, the class is fully encapsulated.


Dog breeders work to make sure their pups inherit the best traits of a given breed. Some breeds are bred to protect their owners' family and property, whereas others are bred to get along with people. A breeder may want to improve the temperament of his dogs, and so he might breed more dogs who include a good temperament even though some other trait, such as size, may not be optimum. Whatever the breeder does shows up in the way the litter looks and acts. The pups inherit the characteristics of their parents.

Inheritance in OOP works the same way. A class can inherit the characteristics of a class from which it sprang. A "parent" class is called a superclass, whereas the "children" of an existing class are called a subclass. The subclass inherits all its superclass's characteristics, plus it can have unique characteristics of its own.

In Flash Pro, several classes are built in, and you can use a built-in class or a user class to create a subclass. For example, suppose you want a method in the Array class that will return the top element but not remove it from the array, like the pop method does. Also, you want to know when the array is empty, so you want a method that tells you that as well. Using inheritance and the extends statement, all of this is possible (see Listing 3.1). First, create an AS file with the class definition as an extension of the Array class. You want to return the top element in the array; because array element references begin with 0, you want to find the length of the array and subtract 1 to get the top element. Next, all you need is a method that returns a Boolean true if the array is empty.

Listing 3.1 Adding New Features to an Existing Class (Stack.as)

//Stack class
dynamic class Stack extends Array {
 var Stack:Array = new Array();
 function top() {
 return this[this.length-1];
 function isEmpty():Boolean {
 return this.length == 0;

To test this script, you need to see whether the new method top() will indeed return the top element in the array without removing it. First, invoke the top() method and then check the length of the array. If the length of the array is the original size, everything is working. Next, after using the pop() method three times to empty the array, use the isEmpty() method. The script in Listing 3.2 requires a multiline dynamic text field with the instance name zoo_txt on the Stage.

Listing 3.2 Using the New and Inherited Features of an Extended Class (StackTop.FLA)

var popMe:Stack = new Stack();
popMe.push("Lions", "Tigers", "Elephants");
zoo_txt.text = popMe.top()+newline;
zoo_txt.text += "Length:" + popMe.length + newline;
zoo_txt.text += popMe.pop()+newline;
zoo_txt.text += popMe.pop()+newline;
zoo_txt.text += popMe.pop()+newline;
zoo_txt.text += "Empty:" + popMe.isEmpty();

When you test the new class, Stack, you will find that you can now successfully use all the inherited characteristics of the Array class plus the new methods you added to the subclass, Stack.


The third element of the OOP foundation is polymorphism. At its simplest, polymorphism simply means taking on several forms. In programming, polymorphism refers to using the same method or operation to do different things. One context generates one action, and another context generates another. For example, anyone who has used the add operator (+) in a program is aware that in one context the operator adds two values, and in another context it concatenates strings. The following shows a simple example of polymorphism with the add operator:

29 + 31 = 60
"29" + "31" = 2931

As the context changes, so does the meaning and use of the add operator, but the operator looks exactly the same no matter what it's doing.

Perhaps the most appropriate way to think about polymorphism is in terms of parent classes (superclasses) and child classes (subclasses). Suppose you create a parent class called MotorVehicle. The MotorVehicle class contains an internal combustion engine method for locomotion, called useEngine(). If you create three different subclasses using the MotorVehicle interface—Airplane, Automobile, and JetSki—all must include the useEngine() method, but each provides the useEngine() differently. If all the subclasses adhere to a common MotorVehicle interface, they all have a useEngine() method. Therefore, the lines


result in different actions appropriate to each subclass, even though the term used, useEngine(), is identical.

Polymorphism is a far more robust and complex concept than what has been presented here, and you'll find more than a single type of polymorphism (such as coercion, overloading, parametric, and inclusion). To learn more about OOP in general and polymorphism specifically, take a look at a good book on object-oriented programming. In this book, when polymorphism is employed in a script, its use will be noted. (Virtually all uses of classes employ encapsulation, and inheritance can be easily spotted by the use of the extends term; therefore, the use of encapsulation and inheritance need not be noted.)

  • + Share This
  • 🔖 Save To Your Account