Home > Articles

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 {
    //Property
     var colorName:String;
     function ColorShow(someColor:String) {
     this.colorName = someColor;
     }
     //Method
     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.

Encapsulation

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.

Inheritance

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.

Polymorphism

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

JetSki.useEngine();
Airplane.useEngine();
Automobile.useEngine();

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.)

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020