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 are Classes in Flash

About object-oriented programming and Flash

The benefits of using classes

About packages

A comparison of classes and packages

Working with packages

About values and data types

Object-oriented programming fundamentals

Writing custom class files

About importing class files

About setting and modifying the classpath

How the compiler resolves class references

Using a class file in Flash

Using methods and properties from a class file

About public, private, and static methods and properties (members)

About class members

Using the Singleton design pattern

Using class members

About getter setter methods

Using getter and setter methods

About dynamic classes

Creating dynamic classes

About using encapsulation

About using the this keyword in classes

Example: Writing custom classes

Creating and packaging your class files

Writing the constructor function

Adding methods and properties

Controlling member access in your classes

Documenting the classes

Importing classes and packages

Compiling and exporting classes

Assigning a class to symbols in Flash

About the conditional operator and alternative syntax

Using ASO files

Understanding classes and scope

About creating a new instance of a built-in class

Accessing built-in object properties

About calling built-in object methods

About class (static) members

Excluding classes

Preloading class files

 
About object-oriented programming and Flash

TOP

ActionScript 2.0 is an object-oriented language. Like ActionScript, OOP languages are based on the concept of classes and instances. A class defines all of the properties that distinguish a series of objects. For example, a User class represents a bunch of users who are using your application. Then, you have an instantiation of the class, which, for the User class, is one of the individual users--one of its members. The instantiation produces an instance of the User class, and that instance has all of the properties of the User class.

Classes are also considered like data types or templates that you can create to define a new type of object. For example, if you need a data type of Lettuce in your application, you might write the Lettuce class. This defines the Lettuce object, and then you can assign your Lettuce methods (wash()) and properties (leafy or bugs). To define a class, you use the class keyword in an external script file. You can create an external script file in the Flash authoring tool by selecting File > New and then selecting ActionScript File.

Flash Player 8, available in both Flash Basic 8 and Flash Professional 8, adds several new features to the ActionScript language such as filter effects, file upload and download, and the External API. As always, ActionScript 2.0 provides several powerful and familiar OOP concepts and keywords (such as class, interface, and package) found in other programming languages, such as Java. The programming language lets you build program structures that are reusable, scalable, robust, and maintainable. It can also decrease development time by providing users with thorough coding assistance and debugging information. You can use ActionScript 2.0 to create objects and establish inheritance and to create custom classes and extend the Flash top-level and built-in classes. You learn how to create classes and use custom classes in this chapter.

Flash Basic 8 and Flash Professional 8 include approximately 65 top-level and built-in classes that provide everything from basic, or "primitive," data types (Array, Boolean, Date, and so on), to custom errors and events, as well as several ways to load external content (XML, images, raw binary data, and more). You can also write your own custom classes and integrate them into your Flash documents or even extend the top-level classes and add your own functionality or modify existing functionality. For example, About class members in this chapter shows you how to make a custom Person class that contains custom properties for the person's name and age. You can then treat this custom class as a new data type in your documents and create a new instance of the class using the new operator.

 

The benefits of using classes

TOP

In OOP, a class defines a category of object. A class describes the properties (data) and methods (behaviors) for an object, much like an architectural blueprint describes the characteristics of a building. You write a custom class in an external ActionScript (AS) file and you can import it into your application when you compile the FLA file.

Classes can be very useful when you build larger Flash applications because you can organize a lot of the application's complexity in external class files. When you move a lot of the logic into a custom class, you can not only make the code easier to reuse, but you can also "hide" some of the methods and properties from other parts of the ActionScript code. This helps you prevent people from accessing sensitive information or changing data that shouldn't be changed.

When you use a class, you can also extend existing classes and add new functionality or modify existing functionality. For example, if you create three very similar classes, you can write a base class and then write two other classes that extend the base class. These two classes can add additional methods and properties, so that you don't need to create three class files that all duplicate the same code and logic.

Another benefit of using classes is code reusability. For example, if you create a custom class that creates a custom progress bar using the Drawing application programming interface (API), you could save the progress bar class in your classpath and reuse the same code in all of your Flash documents by importing the custom class.

 

About packages

TOP

When you are creating classes, you organize your ActionScript class files in packages. A package is a directory that contains one or more class files and that resides in a designated classpath directory. A package can, in turn, contain other packages, called subpackages, each with its own class files.

Like variables, package names must be identifiers; that is, the first character can be a letter, underscore (_), or dollar sign ($), and each subsequent character can be a letter, number, underscore, or dollar sign. There are preferred ways to name packages, which for example recommend that you avoid using underscores or dollar sign characters.

Packages are commonly used to organize related classes. For example, you might have three related classes, Square, Circle, and Triangle, that are defined in Square.as, Circle.as, and Triangle.as. Assume that you've saved the ActionScript files to a directory specified in the classpath, as shown in the following example:

// In Square.as:

class Square {}

// In Circle.as:

class Circle {}

// In Triangle.as:

class Triangle {}

Because these three class files are related, you might decide to put them in a package (directory) called Shapes. In this case, the fully qualified class name would contain the package path, as well as the simple class name. Package paths are denoted with dot (.) syntax, where each dot indicates a subdirectory.

For example, if you placed each ActionScript file that defines a shape in the Shapes directory, you would need to change the name of each class file to reflect the new location, as follows:

// In Shapes/Square.as:

class Shapes.Square {}

// In Shapes/Circle.as:

class Shapes.Circle {}

// In Shapes/Triangle.as:

class Shapes.Triangle {}

To reference a class that resides in a package directory, you can either specify its fully qualified class name or import the package by using the import statement.

 

A comparison of classes and packages

TOP

In OOP, a class defines a category of object. Classes are essentially data types that you can create if you want to define a new type of object in your application. A class describes the properties (data) and behaviors (methods) for an object, much like an architectural blueprint describes the characteristics of a building. The properties (variables defined within a class) and methods of a class are collectively called the class's members. To use the properties and methods defined by a class, you generally first create an instance of that class (except for classes that have all static members. The relationship between an instance and its class is similar to the relationship between a house and its blueprints.

Packages in Flash are directories that contain one or more class files and reside in a designated file path. You might place related custom class files within a single directory. For example, you might have three related classes called SteelWidget, PlasticWidget, and WoodWidget that are defined in SteelWidget.as, PlasticWidget.as, and WoodWidget.as. You would organize these classes in the Widget package.

 

Working with packages

TOP

Packages are directories that contain one or more class files and reside in a designated classpath directory. For example, the flash.filters package is a directory on your hard disk that contains several class files for each filter type (such as BevelFilter, BlurFilter, DropShadowFilter, and so on) in Flash 8.

NOTE : To use the import statement, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box.

The import statement lets you access classes without specifying their fully qualified names. For example, if you want to use the BlurFilter class in a script, you must refer to it by its fully qualified name (flash.filters.BlurFilter) or import it; if you import it, you can refer to it by its class name (BlurFilter). The following ActionScript code demonstrates the differences between using the import statement and using fully qualified class names.

If you don't import the BlurFilter class, your code needs to use the fully qualified class name (package name followed by class name) in order to use the filter:

// without importing

var myBlur:flash.filters.BlurFilter = new flash.filters.BlurFilter(10, 10, 3);

The same code, written with an import statement, lets you access the BlurFilter using only the class name instead of always having to use the fully qualified name. This can save typing and reduce the chance of making typing mistakes:

// with importing

import flash.filters.BlurFilter;

var myBlur:BlurFilter = new BlurFilter(10, 10, 3);

If you were importing several classes within a package (such as the BlurFilter, DropShadowFilter, and GlowFilter) you could use one of two methods of importing each class. The first method of importing multiple classes is to import each class using a separate import statement, as seen in the following snippet:

import flash.filters.BlurFilter;

import flash.filters.DropShadowFilter;

import flash.filters.GlowFilter;

Using individual import statements for each class within a package can quickly become very time consuming and prone to typing mistakes. The second method of importing classes within a package is to use a wildcard import that imports all classes within a certain level of a package. The following ActionScript shows an example of using a wildcard import:

import flash.filters.*; // imports each class within flash.filters package

The import statement applies only to the current script (frame or object) in which it's called. For example, suppose on Frame 1 of a Flash document you import all the classes in the macr.util package. On that frame, you can reference classes in that package by their class names instead of their fully qualified names. If you wanted to use the class name on another frame script, however, you would need to reference classes in that package by their fully qualified names or add an import statement to the other frame that imports the classes in that package.

When using import statements, it's also important to note that classes are imported only for the level specified. For example, if you imported all classes in the mx.transitions package, only those classes within the /transitions/ directory are imported, not all classes within subdirectories (such as the classes in the mx.transitions.easing package).

TIP : If you import a class but don't use it in your script, the class isn't exported as part of the SWF file. This means you can import large packages without being concerned about the size of the SWF file; the bytecode associated with a class is included in a SWF file only if that class is actually used.

 

About values and data types

TOP

Data, values, and types are important when you start writing classes and using them. You learned about data and types in Data and Data Types. When you work with classes, remember that data types describe the kind of information a variable or ActionScript element can contain, such as Boolean, Number, and String. For more information, see About data types.

Expressions have values, while values and properties have types. The values that you can set and get to and from a property in your class must be compatible with that property. Type compatibility means the type of a value is compatible with the type that is in use, such as the following example:

var myNum:Number = 10;

 

Object-oriented programming fundamentals

TOP

In the following sections, you will examine some of the terminology used throughout this chapter before you start writing ActionScript code. This brief introduction to principles involved in developing object-oriented programs helps you follow the examples and sections within this chapter and the rest of this book. These principles are described in more depth in the rest of this chapter, along with details on how they are implemented in Flash 8.

The following sections use the analogy of a cat, demonstrating how cats might compare to OOP concepts.

Objects :

Think of a real-world object, such as a cat. A cat could be said to have properties (or states), such as name, age, and color; a cat also has behaviors such as sleeping, eating, and purring. In the world of OOP, objects also have properties and behaviors. Using object-oriented techniques, you can model a real-world object (such as a cat) or a more abstract object (such as a chemical process).

NOTE : The word behaviors is used generically here and does not refer to the Behaviors panel in the Flash authoring environment.

Instances and class members

Continuing with the real-world analogy of a cat, consider that there are cats of different colors, ages, and names, with different ways of eating and purring. But despite their individual differences, all cats are members of the same category, or in OOP terms, the same class: the class of cats. In OOP terminology, each individual cat is said to be an instance of the Cat class.

Likewise in OOP, a class defines a blueprint for a type of object. The characteristics and behaviors that belong to a class are jointly referred to as members of that class. The characteristics (in the cat example, the name, age, and color) are called properties of the class and are represented as variables; the behaviors (play, sleep) are called methods of the class and are  represented as functions.

Inheritance :

One of the primary benefits of OOP is that you can create subclasses of (or extend) a class; the subclass then inherits all the properties and methods of the class. The subclass typically defines additional methods and properties or overrides methods or properties defined in the superclass. Subclasses can also override (provide their own definitions for) methods defined in a superclass.

One of the major benefits of using a superclass/subclass structure is that it is easier to reuse similar code between various classes. For example, you could build a superclass called Animal, which contains common characteristics and behaviors of all animals. Next you could build several subclasses that inherit from the Animal superclass and add characteristics and behaviors specific to that type of animal.

You might create a Cat class that inherits from another class. For example, you might create a Mammal class that defines certain properties and behaviors common to all mammals. You could then create a Cat subclass that extends the Mammal class. Another subclass, say, the Siamese class, could extend (subclass) the Cat class, and so on.

Writing subclasses lets you reuse code. Instead of recreating all the code common to both classes, you can simply extend an existing class.

TIP : In a complex application, determining how to structure the hierarchy of your classes is an important part of the design process. Make sure you determine this hierarchy before you begin to program.

Interfaces :

Interfaces in OOP can be described as templates of class definitions, and classes that implement interfaces are required to implement that template of methods. Using the cat analogy, an interface is similar to a blueprint of a cat: the blueprint tells you which parts you need, but not necessarily how those parts are assembled, or how the parts work.

You can use interfaces to add structure and ease of maintenance to your applications. Because ActionScript 2.0 supports extending only from a single superclass, you can use interfaces as a form of limited multiple inheritance.

You can also think of an interface as a "programming contract" that you can use to enforce relationships between otherwise unrelated classes. For example, suppose you are working with a team of programmers, each of whom is working on a different part (class) of the same application. While designing the application, you agree on a set of methods that the different classes use to communicate. So you create an interface that declares these methods, their parameters, and their return types. Any class that implements this interface must provide definitions for those methods; otherwise, a compiler error results.

Encapsulation :

In elegant object-oriented design, objects are seen as "black boxes" that contain, or encapsulate, functionality. A programmer should be able to interact with an object by knowing only its properties, methods, and events (its programming interface), without knowing the details of its implementation. This approach enables programmers to think at higher levels of abstraction and provides an organizing framework for building complex systems.

Encapsulation is why ActionScript 2.0 includes, for example, member access control, so details of the implementation can be made private and invisible to code outside an object. The code outside the object is forced to interact with the object's programming interface rather than with the implementation details (which can be hidden in private methods and properties). This approach provides some important benefits; for example, it lets the creator of the object change the object's implementation without requiring any changes to code outside of the object--that is, as long as the programming interface doesn't change.

Polymorphism :

OOP 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. In Flash, subclasses can define specialized implementations of methods inherited from its superclass but cannot access the superclass's implementation as in other programming languages.

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.

 

Writing custom class files

TOP

The following example examines the parts of a class file. You learn how to write a class, and how you can modify the class to extend the ways that you can use it with Flash. You learn about the parts of a class and how to import them as well as related information about working with custom class files in Flash.

You begin by looking at a very simple class. The following example shows the organization of a simple class called UserClass.

To define a class, you use the class keyword in an external script file (that is, not in a script you are writing in the Actions panel). The class structure is also pertinent for interface files. This structure is illustrated below, and following this illustration you create a class.

  • The class file begins with documentation comments that include a general description of the code as well as author and version information.

  • Add your import statements (if applicable).

  • Write a package statement, class declaration, or interface declaration, as follows:

  • class UserClass {...}

  • Include any necessary class or interface implementation comments. In these comments, add information that is pertinent for the entire class or interface.

  • Add all your static variables. Write the public class variables first and follow them with private class variables.

  • Add instance variables. Write the public member variables first, and follow them with private member variables.

  • Add the constructor statement, such as the one in the following example:

  • public function UserClass(username:String, password:String) {...}

  • Write your methods. Group methods by their functionality, not by their accessibility or scope. Organizing methods this way helps improve the readability and clarity of your code.

  • Write the getter/setter methods into the class file.

The following example looks at a simple ActionScript class named User.

To create class files:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Select File > Save As and name the new file User.as.

  3. Type the following ActionScript code into the Script window:

    /**

    User class

    author: John Doe

    version: 0.8

    modified: 08/21/2005

    copyright: Macromedia, Inc.

    This code defines a custom User class that allows you to create new users and specify user login information.

    */

    class User {

    // private instance variables

    private var __username:String;

    private var __password:String;

    // constructor statement

    public function User(p_username:String, p_password:String) {

    this.__username = p_username;

    this.__password = p_password;

    }

    public function get username():String {

    return this.__username;

    }

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

    this.__username = value;

    }

    public function get password():String {

    return this.__password;

    }

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

    this.__password = value;

    }

    }

  4. Save your changes to the class file.

    The previous code snippet begins with a standardized documentation comment, which specifies the class name, author, version, date the class was last modified, copyright information, and a brief description of what the class does.

    The User class's constructor statement takes two parameters: p_username and p_password, which are copied into the class's private instance variables __username and __password. The remainder of the code in the class defines the getter and setter properties for the private instance variables. If you want to create a read-only property, then you would define a getter function, but not a setter function. For example, if you want to make sure a user name cannot be changed after it has been defined, you would delete the username setter function in the User class file.

  5. Select File > New and then select Flash Document.

  6. Select File > Save As and name the file user_test.fla. Save the file in the same directory as User.as.

  7. Type the following ActionScript into Frame 1 of the Timeline:

    import User;

    var user1:User = new User("un1", "pw1");

    trace("Before:");

    trace("\t username = " + user1.username); // un1

    trace("\t password = " + user1.password); // pw1

    user1.username = "1nu";

    user1.password = "1wp";

    trace("After:");

    trace("\t username = " + user1.username); // 1nu

    trace("\t password = " + user1.password); // 1wp

    Because the User class you created previously is very basic, the ActionScript in the Flash document is also very straightforward. The first line of code imports the custom User class into your Flash document. Importing the User class lets you use the class as a custom data type.

    A single instance of the User class is defined and assigned to a variable named user1. You assign the user1 User object a value and define a username of un1 and a password of pw1. The following two trace statements display the current value of user1.username and user1.password using the User class's getter functions, which both return strings. The next two lines use the User class's setter functions to set new values for the username and password variables. Finally, you trace the values for username and password to the Output panel. The trace statements display the modified values that you set using the setter functions.

  8. Save the FLA file, and then select Control > Test Movie to test the files.

You see the results of the trace statements in the Output panel. In the next examples, you use these files in an application.

A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. The rest of the functionality resides in a custom class file, XmlMenu.as.

 

About importing class files

TOP

In order to use a class or interface that you've defined, Flash must locate the external ActionScript files that contain the class or interface definition so that it can import the file. The list of directories in which Flash searches for class, interface, function, and variable definitions is called the classpath. Flash has two classpath settings--a global classpath and a document-level classpath:

  • Global classpath is a classpath that's shared by all Flash documents. You set it in the Preferences dialog box (Edit > Preferences (Windows) or Flash > Preferences (Macintosh), click ActionScript in the Category list, and then click ActionScript 2.0 Settings).

  • Document-level classpath is a classpath that you specifically define for a single Flash document. It is set in the Publish Settings dialog box (File > Publish Settings, select the Flash tab, and then click the Settings button).

When you import class files, the following rules apply

  • The import statements can exist in the following locations:

    • Anywhere before the class definition in class files

    • Anywhere in frame or object scripts

    • Anywhere in ActionScript files that you include in an application (using the #include statement).

  • You import individual, packaged definitions using this syntax:

    • import flash.display.BitmapData;

  • You can import entire packages using the wildcard syntax:

    • import flash.display.*;

You can also include ActionScript code in a Flash document (FLA) file using an include statement. The following rules apply to the include statement:

  • include statements are essentially a copy and paste of the content inside the included ActionScript file.

  • include statements inside ActionScript class files are relative to the subdirectory that contains the file.

  • An include statement in a FLA file can only bring in code that is valid inside FLA files, and the same goes for other places that include statements can live. For example, if you have an include statement inside a class definition, only property and method definitions can exist in the included ActionScript file:

    // Foo.as

    class Foo {

    #include "FooDef.as"

    }

    // FooDef.as:

    var fooProp;

    function fooMethod() {}

    trace("Foo"); // This statement is not permitted in a class definition.

 

About setting and modifying the classpath

TOP

In order to use a class or interface that you've defined, Flash must locate the external ActionScript files that contain the class or interface definition. The list of directories in which Flash searches for class and interface definitions is called the classpath.

When you create an ActionScript class file, you need to save the file to one of the directories specified in the classpath or a subdirectory therein. (You can modify the classpath to include the desired directory path). Otherwise, Flash won't be able to resolve, that is, locate, the class or interface specified in the script. Subdirectories that you create within a classpath directory are called packages and let you organize your classes. (For more information on packages, see Creating and packaging your class files.)

Flash has two classpath settings: a global classpath and a document-level classpath. The global classpath is a classpath that's shared by all of your Flash documents. The document-level classpath is a classpath that you specifically define for a single Flash document.

The global classpath applies to external ActionScript files and to FLA files, and you set it in the Preferences dialog box (Windows: Edit > Preferences (Windows) or Flash > Preferences (Macintosh), select ActionScript from the Category list, and then click ActionScript 2.0 Settings). You can set the document-level classpath in the Flash document's Publish Settings dialog box (File > Publish Settings, select the Flash tab, and then click the Settings button).

NOTE : When you click the Check Syntax button above the Script pane while editing an ActionScript file, the compiler looks only in the global classpath. ActionScript files aren't associated with FLA files in Edit mode and don't have their own classpath.

Using a global classpath

The global classpath is a classpath that's shared by all of your Flash documents.

You can modify the global classpath using the Preferences dialog box. To modify the document-level classpath setting, you use the Publish Settings dialog box for the FLA file. In both cases, you can add absolute directory paths (for example, C:/my_classes) and relative directory paths (for example, ../my_classes or "."). The order of directories in the dialog box reflects the order in which they are searched.

By default, the global classpath contains one absolute path and one relative path. The absolute path is denoted by $(LocalData)/Classes in the Preferences dialog box. The location of the absolute path is shown here:

  • Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Adobe\Flash cs\language\Configuration\Classes.

  • Macintosh: Hard Disk/Users/user/Library/Application Support/Adobe/Flash cs/language/Configuration/Classes.

    NOTE : Do not delete the absolute global classpath. Flash uses this classpath to access built-in classes. If you accidentally delete this classpath, reinstate it by adding $(LocalData)/Classes as a new classpath.

The relative path portion of the global classpath is denoted by a single dot (.) and points to the current document directory. Be aware that relative classpaths can point to different directories, depending on the location of the document being compiled or published.

You can use the following steps to add a global classpath or edit an existing classpath.

To modify the global classpath:

  1. Select Edit > Preferences (Windows) or Flash > Preferences (Macintosh) to open the Preferences dialog box.

  2. Click the ActionScript in the left column, and then click the ActionScript 2.0 Settings button.

  3. Click the Browse to Path button to browse to the directory you want to add.

  4. Browse to the path that you want to add and click OK.

To delete a directory from the classpath:

  1. Select the path in the Classpath list.

  2. Click the Remove from Path button.

    NOTE : Do not delete the absolute global classpath. Flash uses this classpath to access built-in classes. If you accidentally delete this classpath, you can reinstate it by adding
    $(LocalData)/Classes as a new classpath.

Using a document-level classpath

The document-level classpath applies only to FLA files. You set the document-level classpath in the Publish Settings dialog box for a particular FLA file (File > Publish Settings, then click the Flash tab, and then click ActionScript 2.0 Settings). The document-level classpath is empty by default. When you create and save a FLA file in a directory, that directory becomes a designated classpath directory.

When you create classes, in some cases you might want to store them in a directory that you then add to the list of global classpath directories in the following situations:

  • If you have a set of utility classes that all your projects use

  • If you want to check the syntax of your code (click the Check Syntax button) that's within the external ActionScript file

Creating a directory prevents the loss of custom classes if you ever uninstall and reinstall Flash, especially if the default global classpath directory is deleted and overwritten, because you would lose any classes that you stored in that directory.

For example, you might create a directory such as the following for your custom classes:

  • Windows: Hard Disk\Documents and Settings\user\custom classes.

  • Macintosh: Hard Disk/Users/user/custom classes.

Then, you would add this path to the list of global classpaths (see Using a global classpath).

When Flash attempts to resolve class references in a FLA script, it first searches the document-level classpath specified for that FLA file. If Flash doesn't find the class in that classpath, or if that classpath is empty, it searches the global classpath. If Flash doesn't find the class in the global classpath, a compiler error occurs.

To modify the document-level classpath:

  1. Select File > Publish Settings to open the Publish Settings dialog box.

  2. Click the Flash tab.

  3. Click the Settings button next to the ActionScript Version pop-up menu.

  4. You can either manually type a file path or you can click the Browse to Path button to browse to the directory you want to add to the classpath.

NOTE : To edit an existing classpath directory, select the path in the Classpath list, click the Browse to Path button, browse to the directory you want to add, and click OK.

NOTE : To delete a directory from the classpath, select the path in the Classpath list, and click the Remove Selected Path (-) button.

 

How the compiler resolves class references

TOP

When Flash attempts to resolve class references in a FLA script, it first searches the document-level classpath specified for that FLA file. If the class is not found in that classpath, or if that classpath is empty, Flash searches the global classpath. If the class is not found in the global classpath, a compiler error occurs.

In Flash Professional, when you click the Check Syntax button while editing an ActionScript file, the compiler looks only in the global classpath; ActionScript files aren't associated with FLA files in Edit mode and don't have their own classpath.

 

Using a class file in Flash

TOP

To create an instance of an ActionScript class, use the new operator to invoke the class's constructor function. The constructor function always has the same name as the class and returns an instance of the class, which you typically assign to a variable. For example, if you were using the User class from Writing custom class files, you would write the following code to create a new User object:

var firstUser:User = new User();

NOTE : In some cases, you don't need to create an instance of a class to use its properties and methods. For more information on class (static) members, see About class (static) members and Static methods and properties.

Use the dot (.) operator to access the value of a property in an instance. Type the name of the instance on the left side of the dot, and the name of the property on the right side. For example, in the following statement, firstUser is the instance and username is the property:

firstUser.username

You can also use the top-level or built-in classes that make up the ActionScript language in a Flash document. For example, the following code creates a new Array object and then shows its length property:

var myArray:Array = new Array("apples", "oranges", "bananas");

trace(myArray.length); // 3

 

Using methods and properties from a class file

TOP

In OOP, members (properties or methods) of a class can be instance members or class members. Instance members are created for each instance of the class; they are defined to the prototype of the class when they are initialized in the class definition. In contrast, class members are created once per class. (Class members are also known as static members.)
Properties are attributes that define an object. For example, length is a property of all arrays that specifies the number of elements in the array. Methods are functions that you associate with a class.

The following example shows you how you would create a method in a class file:

class Sample {

public function myMethod():Void {

trace("myMethod");

}

}

Next you could invoke that method in your document. To invoke an instance method or access an instance property, you reference an instance of the class. In the following example, picture01, an instance of the custom Picture class (available in the following exercise), invokes the showInfo() method:

var img1:Picture = new Picture("http://www.helpexamples.com/flash/images/image1.jpg");

// Invoke the showInfo() method.

img1.showInfo();

The next example demonstrates how you can write a custom Picture class to hold various pieces of information about a photo.

To use the Picture and PictureClass classes in a FLA file:

  1. Select File > New and then select ActionScript File. Save the document as Picture.as and then click OK.

  2. You write your custom Picture class in this document.

    Type the following ActionScript code into the Script window:

    /**

    Picture class

    author: John Doe

    version: 0.53

    modified: 6/24/2005

    copyright: Macromedia, Inc.

    The Picture class is used as a container for an image and its URL.

    */

    class Picture {

    private var __infoObj:Object;

    public function Picture(src:String) {

    this.__infoObj = new Object();

    this.__infoObj.src = src;

    }

    public function showInfo():Void {

    trace(this.toString());

    }

    private function toString():String {

    return "[Picture src=" + this.__infoObj.src + "]";

    }

    public function get src():String {

    return this.__infoObj.src;

    }

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

    this.__infoObj.src = value;

    }

    }

  3. Save the ActionScript file.

  4. Select File > New and then select Flash Document to create a new FLA file. Save it as picture_test.fla in the same directory as you saved the Picture class file.

  5. Type the following ActionScript code into Frame 1 of the Timeline:

    var picture1:Picture = new Picture("http://www.helpexamples.com/flash/images/image1.jpg");

    picture1.showInfo();

    this.createEmptyMovieClip("img_mc", 9);

    img_mc.loadMovie(picture1.src);

  6. Save the Flash document.

  7. Select Control > Test Movie to test the document.

    The following text is displayed in the Output panel:

    [Picture src=http://www.helpexamples.com/flash/images/image1.jpg]

A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. The rest of the functionality resides in a custom class file, XmlMenu.as.

 

About public, private, and static methods and properties (members)

TOP

When you write ActionScript class files in an external script file, there are four types of methods and properties that you can create: public methods and properties, private methods and properties, public static methods and properties, and private static methods and properties. These methods and properties define how Flash can access variables, and they allow you to specify what parts of your code can access certain methods or properties.

When you are building class-based applications, whether the application is small or large, it is especially important to consider whether a method or property should be private or public. Considering this ensures that your code is as secure as possible. For example, if you were building a User class, you might not want to allow people using the class to be able to change a user's ID. By setting the class property (sometimes referred to as an instance member) to private, you can limit access to the property to code within the class or subclasses of that class, meaning that no users can change that property directly.

Public methods and properties

The public keyword specifies that a variable or function is available to any caller. Because variables and functions are public by default, the this keyword is used primarily for stylistic and readability benefits, indicating that the variable exists in the current scope. For example, you might want to use the this keyword for consistency in a block of code that also contains private or static variables. The this keyword can be used with either the public or private keyword.

The following Sample class already has a public method named myMethod():

class Sample {

private var ID:Number;

public function myMethod():Void {

this.ID = 15;

trace(this.ID); // 15

trace("myMethod");

}

}

If you want to add a public property, you use the word "public" instead of "private," as you can see in the following sample code:

class Sample {

private var ID:Number;

public var email:String;

public function myMethod():Void {

trace("myMethod");

}

}

Because the email property is public, you can change it within the Sample class, or directly within a FLA.

Private methods and properties

The private keyword specifies that a variable or function is available only to the class that declares or defines it or to subclasses of that class. By default, a variable or function is public, and available to any caller. Use the this keyword if you want to restrict access to a variable or function, as you can see in the following example:

class Sample {

private var ID:Number;

public function myMethod():Void {

this.ID = 15;

trace(this.ID); // 15

trace("myMethod");

}

}

If you want to add a private property to the previous class, you simply use the keyword private before the var keyword.

If you attempt to access the private ID property from outside the Sample class, you get a compiler error and a message in the Output panel. The message indicates that the member is private and cannot be accessed.

Static methods and properties

The static keyword specifies that a variable or function is created only once per class rather than in every object based on that class. You can access a static class member without creating an instance of the class. Static methods and properties can be set in either the public or private scope.

Static members, also called class members, are assigned to the class, not to any instance of the class. To invoke a class method or access a class property, you reference the class name, rather than a specific instance of the class, as shown in the following code:

trace(Math.PI / 8); // 0.392699081698724

If you type this single line of code in the script pane of the Actions panel, you see a result trace in the Output panel.

For example, in the previous Sample class example, you could create a static variable to keep track of how many instances of the class have been created, as demonstrated in the following code:

class Sample {

public static var count:Number = 0;

private var ID:Number;

public var email:String;

public function Sample() {

Sample.count++;

trace("count updated: " + Sample.count);

}

public function myMethod():Void {

trace("myMethod");

}

}

Every time you create a new instance of the Sample class, the constructor method traces the total number of Sample class instances that have been defined so far.

Some of the top-level ActionScript classes have class members (or static members), as you saw earlier in this section when you called the Math.PI property. Class members (properties and methods) are accessed or invoked on the class name, not on an instance of the class. Therefore, you don't create an instance of the class to use those properties and methods.

For example, the top-level Math class consists only of static methods and properties. To call any of its methods, you don't create an instance of the Math class. Instead, you simply call the methods on the Math class itself. The following code calls the sqrt() method of the Math class:

var squareRoot:Number = Math.sqrt(4);

trace(squareRoot); // 2

The following code invokes the max() method of the Math class, which determines the larger of two numbers:

var largerNumber:Number = Math.max(10, 20);

trace(largerNumber); // 20

A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. The rest of the functionality resides in a custom class file, XmlMenu.as.

 

About class members

TOP

Most of the members (methods and properties) discussed so far in this chapter are of a type called instance members. For each instance member, there's a unique copy of that member in every instance of the class. For example, the email member variable of the Sample class has an instance member, because each person has a different e-mail address.

Another type of member is a class member. There is only one copy of a class member, and you use it for the entire class. Any variable declared within a class, but outside a function, is a property of the class. In the following example, the Person class has two properties, age and username, of type Number and String, respectively:

class Person {

public var age:Number;

public var username:String;

}

Similarly, any function declared within a class is considered a method of the class. In the Person class example, you can create a method called getInfo():

class Person {

public var age:Number;

public var username:String;

public function getInfo():String {

// getInfo() method definition

}

}

In the previous code snippet the Person class's getInfo() method, as well as the age and username properties, are all public instance members. The age property would not be a good class member, because each person has a different age. Only properties and methods that are shared by all individuals of the class should be class members.

Suppose that you want every class to have a species variable that indicates the proper Latin name for the species that the class represents. For every Person object, the species is Homo sapiens. It would be wasteful to store a unique copy of the string "Homo sapiens" for every instance of the class, so this member should be a class member.

Class members are declared with the static keyword. For example, you could declare the species class member with the following code:

class Person {

public static var species:String = "Homo sapiens";

// ...

}

You can also declare methods of a class to be static, as shown in the following code:

public static function getSpecies():String {

return Person.species;

}

Static methods can access only static properties, not instance properties. For example, the following code results in a compiler error because the class method getAge() references the instance variable age:

class Person {

public var age:Number = 15;

// ...

public static function getAge():Number {

return age; /* **Error**: Instance variables cannot be accessed in static functions. */

}

}

To solve this problem, you could either make the method an instance method or make the variable a class variable.

A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. The rest of the functionality resides in a custom class file, XmlMenu.as.

 

Using the Singleton design pattern

TOP

A common way to use class members is with the Singleton design pattern. A design pattern defines a formal approach for structuring your code. Typically, you might structure a design pattern as a solution for a common programming problem. There are many established design patterns, such as Singleton. The Singleton design pattern makes sure that a class has only one instance and provides a way of globally accessing the instance.

Often you encounter situations when you need exactly one object of a particular type in a system. For example, in a chess game, there is only one chessboard, and in a country, there is only one capital city. Even though there is only one object, you should encapsulate the functionality of this object in a class. However, you might need to manage and access the one instance of that object. Using a global variable is one way to do this, but global variables are not desirable for most projects. A better approach is to make the class manage the single instance of the object itself using class members. The following example shows a typical Singleton design pattern usage, where the Singleton instance is created only once.

To use the Singleton design pattern:

  1. Select File > New and then select ActionScript File. Save the document as Singleton.as.

  2. Type the following ActionScript code into the Script window:

    /**

    Singleton class

    author: John Doe

    version: 0.53

    modified: 6/24/2008

    copyright: Macromedia, Inc.

    */

    class Singleton {

    private static var instance:Singleton = null;

    public function trackChanges():Void {

    trace("tracking changes.");

    }

    public static function getInstance():Singleton {

    if (Singleton.instance == null) {

    trace("creating new Singleton.");

    Singleton.instance = new Singleton();

    }

    return Singleton.instance;

    }

    }

  3. Save the Singleton.as document.

  4. Select File > New and then select Flash Document to create a new FLA file, and save it as singleton_test.fla in the same directory as you saved the Singleton class file.

  5. Type the following ActionScript code into Frame 1 of the Timeline:

    Singleton.getInstance().trackChanges(); // tracking changes.

    var s:Singleton = Singleton.getInstance(); // tracking changes.

    s.trackChanges();

  6. Save the Flash document.

  7. Select Control > Test Movie to test the document.

The Singleton object is not created until you need it--that is, until some other code asks for it by calling the getInstance() method. This is typically called lazy creation, and it can help make your code more efficient in many circumstances.

Remember not to use too few or too many class files for your application, because doing so can lead to poorly designed class files, which are not beneficial to the application's performance or to your workflow. You should always attempt to use class files instead of placing code in other places (such as timelines); however, avoid creating many classes that have only a small amount of functionality or only a few classes that handle a lot of functionality. Both of these scenarios might indicate poor design.

 

Using class members

TOP

One use of class (static) members is to maintain state information about a class and its instances. For example, suppose you want to keep track of the number of instances that have been created from a particular class. An easy way to do this is to use a class property that increments each time a new instance is created.

In the following example, you'll create a class called Widget that defines a single, static instance counter named widgetCount. Each time a new instance of the class is created, the value of widgetCount increments by 1 and the current value of widgetCount is displayed in the Output panel.

To create an instance counter using a class variable:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Type the following code into the Script window:

    class Widget {

    //Initialize the class variable

    public static var widgetCount:Number = 0;

    public function Widget() {

    Widget.widgetCount++;

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

    }

    }

    The widgetCount variable is declared as static, so it initializes to 0 only once. Each time the Widget class's constructor statement is called, it adds 1 to widgetCount and then shows the number of the current instance that's being created.

  3. Save your file as Widget.as.

  4. Select File > New and then select Flash Document to create a new FLA, and save it as widget_test.fla in the same directory as Widget.as.

  5. In widget_test.fla, type the following code into Frame 1 of the Timeline:

    // Before you create any instances of the class,

    // Widget.widgetCount is zero (0).

    trace("Widget count at start: " + Widget.widgetCount); // 0

    var widget1:Widget = new Widget(); // 1

    var widget2:Widget = new Widget(); // 2

    var widget3:Widget = new Widget(); // 3

    trace("Widget count at end: " + Widget.widgetCount); // 3

  6. Save the changes to widget_test.fla.

  7. Select Control > Test Movie to test the file.

    Flash displays the following information in the Output panel:

    Widget count at start: 0

    Creating widget # 1

    Creating widget # 2

    Creating widget # 3

    Widget count at end: 3

 

About getter setter methods

TOP

Getter and setter methods are accessor methods, meaning that they are generally a public interface to change private class members. You use getter and setter methods to define a property. You access getter and setter methods as properties outside the class, even though you define them within the class as methods. Those properties outside the class can have a different name from the property name in the class.

There are some advantages to using getter and setter methods, such as the ability to let you create members with sophisticated functionality that you can access like properties. They also let you create read-only and write-only properties.

Even though getter and setter methods are useful, you should be careful not to overuse them because, among other issues, they can make code maintenance more difficult in certain situations. Also, they provide access to your class implementation, like public members. OOP practice discourages direct access to properties within a class.

When you write classes, you are always encouraged to make as many as possible of your instance variables private and add getter and setter methods accordingly. This is because there are several times when you may not want to let users change certain variables within your classes. For example, if you have a private static method that tracks the number of instances created for a specific class, you don't want a user to modify that counter using code. Only the constructor statement should increment that variable whenever it's called. In this situation, you might create a private instance variable and allow a getter method only for the counter variable, which means users are able to retrieve the current value only by using the getter method, and they won't be able to set new values using the setter method. Creating a getter without a setter is a simple way of making certain variables in your class read-only.

 

Using getter and setter methods

TOP

The syntax for getter and setter methods is as follows:

  • A getter method does not take any parameters and always returns a value.

  • A setter method always takes a parameter and never returns a value.

Classes typically define getter methods that provide read access and setter methods that provide write access to a given property. For example, imagine a class that contains a property called userName:

private var userName:String;

Instead of allowing instances of the class to directly access this property (user.userName = "Buster", for example), the class might have two methods, getUserName() and setUserName(), that would be implemented as shown in the next example.

To use getter and setter methods:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Type the following code into the Script window:

    class Login {

    private var __username:String;

    public function Login(username:String) {

    this.__username = username;

    }

    public function getUserName():String {

    return this.__username;

    }

    public function setUserName(value:String):Void {

    this.__username = value;

    }

    }

  3. Save the ActionScript document as Login.as.

  4. As you can see, getUserName() returns the current value of userName, and setUserName() sets the value of userName to the string parameter passed to the method.

  5. Select File > New and then select Flash Document to create a new FLA, and save it as login_test.fla in the same directory as Login.as.

    Add the following ActionScript to Frame 1 of the main Timeline:

    var user:Login = new Login("RickyM");

    // calling getUserName() method

    var userName:String = user.getUserName();

    trace(userName); // RickyM

    // calling setUserName() method

    user.setUserName("EnriqueI");

    trace(user.getUserName()); // EnriqueI

  6. Select Control > Test Movie to test the file.

    Flash displays the following information in the Output panel:

    RickyM

    EnriqueI

However, if you want to use a more concise syntax, you can use implicit getter and setter methods. Implicit getter and setter methods let you access class properties in a direct manner, while maintaining good OOP practice.

To define these methods, use the get and set method attributes. You create methods that get or set the value of a property, and add the keyword get or set before the method name, as shown in the next example.

NOTE : Implicit getter and setter methods are syntactic shorthand for the Object.addProperty() method found in ActionScript 1.0.

To use implicit getter and setter methods:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Type the following code into the Script window:

    class Login2 {

    private var __username:String;

    public function Login2(username:String) {

    this.__username = username;

    }

    public function get userName():String {

    return this.__username;

    }

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

    this.__username = value;

    }

    }

  3. Save the ActionScript document as Login2.as.

    Remember that a getter method does not take any parameters. A setter method must take exactly one required parameter. A setter method can have the same name as a getter method in the same scope. Getter and setter methods cannot have the same names as other properties. For example, in the previous example code you defined getter and setter methods named userName; in this case you could not also have a property named userName in the same class.

  4. Select File > New and then select Flash Document to create a new FLA, and save it as login2_test.fla in the same directory as Login2.as.

  5. Add the following ActionScript to Frame 1 of the main Timeline:

    var user:Login2 = new Login2("RickyM");

    // calling "get" method

    var userNameStr:String = user.userName;

    trace(userNameStr); // RickyM

    // calling "set" method

    user.userName = "EnriqueI";

    trace(user.userName); // EnriqueI

    Unlike ordinary methods, you invoke getter and setter methods without any parentheses or arguments. You invoke getter and setter methods as you would a property by the same name.

  6. Save the Flash document and select Control > Test Movie to test the file.

    Flash displays the following information in the Output panel:

    RickyM

    EnriqueI

NOTE : You cannot use getter and setter method attributes in interface method declarations.

 

About dynamic classes

TOP

Adding the dynamic keyword to a class definition specifies that objects based on the specified class can add and access dynamic properties at runtime. You should create dynamic classes only if you specifically require this functionality.

Type checking on dynamic classes is less strict than type checking on nondynamic classes, because members accessed inside the class definition and on class instances are not compared with those defined in the class scope. Class member functions, however, can still be type checked for return types and parameter types.

 

Creating dynamic classes

TOP

By default, the properties and methods of a class are fixed. That is, an instance of a class can't create or access properties or methods that weren't originally declared or defined by the class. For example, consider a Person class that defines two properties, userName and age.

To create a class that is not dynamic:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Type the following ActionScript into the Script window:

    class Person {

    public var userName:String;

    public var age:Number;

    }

    If, in another script, you create an instance of the Person class and try to access a property of the class that doesn't exist, the compiler generates an error.

  3. Save the file on your hard disk as Person.as.

  4. Select File > New and then select Flash Document to create a new FLA file, and then click OK.

  5. Select File > Save As, name the file person_test.fla, and save the file in the same directory as the Person class you created earlier.

  6. Add the following code to create a new instance of the Person class (firstPerson), and try to assign a value to a property called hairColor (which doesn't exist in the Person class):

    var firstPerson:Person = new Person();

    firstPerson.hairColor = "blue"; // Error. There is no property with the name 'hairColor'.

  7. Save the Flash document.

  8. Select Control > Test Movie to test the code.

    This code causes a compiler error because the Person class doesn't declare a property named hairColor. In most cases, this is exactly what you want to happen. Compiler errors might not seem desirable, but they are very beneficial to programmers: good error messages help you to write correct code by pointing out mistakes early in the coding process.

In some cases, however, you might want to add and access properties or methods of a class at runtime that aren't defined in the original class definition. The dynamic class modifier lets you do just that.

To create a dynamic class:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Select File > Save As and name the file Person2.as. Save the file on your hard disk.

  3. Type the following code into the Script window:

    dynamic class Person2 {

    public var userName:String;

    public var age:Number;

    }

    This ActionScript adds the dynamic keyword to the Person class in the previous example. Instances of the Person2 class can add and access properties and methods that are not defined in this class.

  4. Save your changes to the ActionScript file.

  5. Select File > New and then select Flash Document to create a new FLA file, and then click OK.

  6. Select File > Save As and name the new file person2_test.fla. Save it in the same directory as Person2.as.

  7. Type the following code to create a new instance of the Person2 class (firstPerson), and assign a value to a property called hairColor (which doesn't exist in the Person2 class).

    var firstPerson:Person2 = new Person2();

    firstPerson.hairColor = "blue";

    trace(firstPerson.hairColor); // blue

  8. Save your changes to the person2_test.fla file.

  9. Select Control > Test Movie to test the code.

    Because the custom Flash class is dynamic, you can add methods and properties to the class at runtime (when the SWF file plays). When you test the code the text blue should be displayed in the Output panel.

When you develop applications, you wouldn't want to make classes dynamic unless you needed to. One reason not to use dynamic classes is that type checking on dynamic classes is less strict than type checking on nondynamic classes, because members accessed inside the class definition and on class instances are not compared with those defined in the class scope. Class member functions, however, can still be type checked for return types and parameter types.

Subclasses of dynamic classes are also dynamic, with one exception. Subclasses of the MovieClip class are not dynamic by default, even though the MovieClip class itself is dynamic. This implementation provides you with more control over subclasses of the MovieClip class, because you can choose to make your subclasses dynamic or not:

class A extends MovieClip {} // A is not dynamic

dynamic class B extends A {} // B is dynamic

class C extends B {} // C is dynamic

class D extends A {} // D is not dynamic

dynamic class E extends MovieClip{} // E is dynamic

 

About using encapsulation

TOP

In elegant object-oriented design, objects are seen as "black boxes" that contain, or encapsulate, functionality. A programmer should be able to interact with an object by knowing only its properties, methods, and events (its programming interface), without knowing the details of its implementation. This approach enables programmers to think at higher levels of abstraction and provides an organizing framework for building complex systems.

Encapsulation is why ActionScript 2.0 includes, for example, member access control, so that details of the implementation can be made private and invisible to code outside an object. The code outside the object is forced to interact with the object's programming interface rather than with the implementation details. This approach provides some important benefits; for example, it lets the creator of the object change the object's implementation without requiring any changes to code outside of the object, as long as the programming interface doesn't change.

An example of encapsulation in Flash would be setting all your member and class variables to private and forcing people who implement your classes to access these variables using getter and setter methods. Performing encapsulation this way ensures that if you ever need to change the structure of the variables in the future, you would need only to change the behavior of the getter and setter functions rather than force every developer to change the way he or she accesses the class's variables.

The following code shows how you could modify the Person class from earlier examples, set its instance members to private, and define getter and setter methods for the private instance members:

class Person {

private var __userName:String;

private var __age:Number;

public function get userName():String {

return this.__userName;

}

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

this.__userName = value;

}

public function get age():Number {

return this.__age;

}

public function set age(value:Number):Void {

this.__age = value;

}

}

 

About using the this keyword in classes

TOP

Use the this keyword as a prefix within your classes for methods and member variables. Although it is not necessary, the this keyword makes it easy to tell that a property or method belongs to a class when it has a prefix; without the keyword, you cannot tell whether the property or method belongs to the superclass.

You can also use a class name prefix for static variables and methods, even within a class. This helps qualify the references you make, which makes code readable. Depending on the coding environment you use, adding prefixes might also trigger code hints.

NOTE : You do not have to add these prefixes, and some developers feel it is unnecessary. Macromedia recommends adding the this keyword as a prefix, because it can aid readability and helps you write clean code by providing context for your methods and variables.

 

Example: Writing custom classes

TOP

Now that you've explored the basics of a class file, and what kinds of things it contains, it's time to learn some of the general guidelines for creating a class file. The first example in this chapter shows you how to write classes and package them. The second example shows you how to use those class files with a FLA file.

CAUTION

ActionScript code in external files is compiled into a SWF file when you publish, export, test, or debug a FLA file. Therefore, if you make any changes to an external file, you must save the file and recompile any FLA files that use it.

As discussed in Writing custom class files, a class consists of two main parts: the declaration and the body. The class declaration consists minimally of the class statement, followed by an identifier for the class name, and then left and right curly braces ({}). Everything inside the braces is the class body, as shown in the following example:

class className {

// class body

}

Remember: you can define classes only in external ActionScript files. For example, you can't define a class in a frame script in a FLA file. Therefore, you create a new file for this example.
In its most basic form, a class declaration consists of the class keyword, followed by the class name (Person, in this case), and then left and right curly braces ({}). Everything between the braces is called the class body and is where the class's properties and methods are defined.

By the end of this example, the basic ordering of your class files is as follows:

  • Documentation comments

  • Class declaration

  • Constructor function

  • Class body

You do not write subclasses in this chapter.

A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. The rest of the functionality resides in a custom class file, XmlMenu.as.

About general guidelines for creating a class

  • The following points are guidelines to follow when you write custom class files. They help you write correct and well-formed classes. You practice these guidelines in upcoming examples.

  • In general, place only one declaration per line, and do not place either the same or different types of declarations on a single line. Format your declarations as the following example shows:

    private var SKU:Number; // product SKU (identifying) number

    private var quantity:Number; // quantity of product

  • Initialize local variables when you declare them, unless that initial value is determined by a calculation.

  • Declare variables before you first use them (including loops). For example, the following code predeclares the loop iterator variable (i) before using it in the for loop:

    var my_array:Array = new Array("one", "two", "three");

    var i:Number;

    for (i = 0 ; i < my_array.length; i++) {

    trace(i + " = " + my_array[i]);

    }

  • Avoid using local declarations that hide higher-level declarations. For example, do not declare a variable twice, as the following example shows: \

    // bad code

    var counter:Number = 0;

    function myMethod() {

    var counter:Number;

    for (counter = 0; counter <= 4; counter++) {

    // statements;

    }

    }

    This code declares the same variable inside an inner block.

  • Do not assign many variables to a single value in a statement, because it is difficult to read, as you can see in the following ActionScript code samples:

    // bad form

    xPos = yPos = 15;

    or

    // bad form

    class User {

    private var m_username:String, m_password:String;

    }

  • Have a good reason for making public instance variables, or public static, class, or member variables. Make sure that these variables are explicitly public before you create them this way.

  • Set most member variables to private unless there is a good reason to make them public. It is much better from a design standpoint to make member variables private and allow access only to those variables through a small group of getter and setter functions.

About naming class files

Class names must be identifiers--that is, the first character must be a letter, underscore (_), or dollar sign ($), and each subsequent character must be a letter, number, underscore, or dollar sign. As a preferred practice, try to always limit class names to letters.

The class name must exactly match the name of the ActionScript file that contains it, including capitalization. In the following example, if you create a class called Rock, the ActionScript file that contains the class definition must be named Rock.as:

// In file Rock.as

class Rock {

// Rock class body

}

 

Creating and packaging your class files

TOP

In this section, you create, name, and package your class files for this example (Example: Writing custom classes). The following sections show you how to write complete (yet simple) class files.

When you create a class file, decide where you want to store the file. In the following steps, you'll save the class file and the application FLA file that uses the class file in the same directory for simplicity. However, if you want to check syntax, you also need to tell Flash how it can find the file. Typically, when you create an application, you add the directory in which you store your application and class files to the Flash classpath.

Class files are also called ActionScript (AS) files. You create AS files in the Flash authoring tool or by using an external editor. Several external editors, such as Adobe Dreamweaver and Adobe Flex Builder, can create AS files.

NOTE : The name of a class (ClassA) must exactly match the name of the AS file that contains it (ClassA.as). This is very important; if these two names don't match exactly, including capitalization, the class won't compile.

To create a class file and class declaration:

  1. Select File > New and then select Flash Document to create a new FLA document, and then click OK.

  2. Select File > Save As, name the new file package_test.fla, and save the Flash document to the current directory.

    You'll add content to this Flash document in a future step.

  3. Select File > New and then select ActionScript File, and then click OK.

  4. Select File > Save As and create a new subdirectory named com, and then do the following:

    1. In the com subdirectory, create a new subdirectory named Adobe.

    2. in the macromedia subdirectory, create an new subdirectory named utils.

    3. Save the current ActionScript document in the utils directory and name the file ClassA.as.

  5. Type the following code into the Script window:

    class com.macromedia.utils.ClassA {

    }

    The preceding code creates a new class named ClassA in the com.macromedia.utils package.

  6. Save the ClassA.as ActionScript document.

  7. Select File > New and then select ActionScript File, and then click OK.

  8. Select File > Save As, name the new file ClassB.as, and save it in the same directory as ClassA.as created in an earlier step.

  9. Type the following code into the Script window:

    class com.macromedia.utils.ClassB {

    }

    The previous code creates a new class named ClassB in the com.macromedia.utils package.

  10. Save your changes to both the ClassA.as and ClassB.as class files.

The class files you use in a FLA file import into a SWF file when you compile it. The code you write in a class file should have a certain methodology and ordering, which are discussed in the following sections.

If you are creating multiple custom classes, use packages to organize your class files. A package is a directory that contains one or more class files and resides in a designated classpath directory. A class name must be fully qualified within the file in which it is declared--that is, it must reflect the directory (package) in which it is stored.

For example, a class named com.macromedia.docs.YourClass is stored in the com/macromedia/docs directory. The class declaration in the YourClass.as file looks like this:

class com.macromedia.docs.YourClass {

// your class

}

NOTE : You write the class declaration that reflects the package directory in the following section, Example: Writing custom classes.

For this reason, it's good practice to plan your package structure before you begin creating classes. Otherwise, if you decide to move class files after you create them, you will have to modify the class declaration statements to reflect their new location.

To package your class files:

  1. Decide on the package name you'd like to use.

    Package names should be intuitive and easily identifiable by fellow developers. Remember that the package name also matches a specific directory structure. For example, any classes in the com.macromedia.utils package needs to be placed in a com/macromedia/utils folder on your hard drive.

  2. Create the required directory structure after you've chosen a package name.

    For example, if your package was named com.macromedia.utils, you would need to create a directory structure of com/macromedia/utils and place your classes in the utils folder.

  3. Use the com.macromedia.utils prefix for any class you create in this package.

    For example, if your class name was ClassA, the full class name would need to be com.macromedia.utils.ClassA within the com/macromedia/utils/ClassA.as class file.

  4. If you change your package structure at a future point, remember to modify not only the directory structure, but the package name within each class file, as well as every import statement or reference to a class within that package.

 

Writing the constructor function

TOP

You have already learned how to write the class declaration in Creating and packaging your class files. In this part of the chapter, you write what's called the class file's constructor function.

NOTE : You learn how to write the comments, statements, and declarations in later sections.

Constructors are functions that you use to initialize (define) the properties and methods of a class. By definition, constructors are functions within a class definition that have the same name as the class. For example, the following code defines a Person class and implements a constructor function. In OOP, the constructor function initializes each new instance of a class.

A class's constructor is a special function that is called automatically when you create an instance of a class using the new operator. The constructor function has the same name as the class that contains it. For example, the Person class you created contained the following constructor function:

// Person class constructor function

public function Person (uname:String, age:Number) {

this.__name = uname;

this.__age = age;

}

Consider the following points when you write constructor functions:

  • If no constructor function is explicitly declared--that is, if you don't create a function whose name matches that of the class--the compiler automatically creates an empty constructor function for you.

  • A class can contain only one constructor function; overloaded constructor functions are not allowed in ActionScript 2.0.

  • A constructor function should have no return type.

The term constructor is also typically used when you create (instantiate) an object based on a particular class. The following statements are calls to the constructor functions for the top-level Array class and the custom Person class:

var day_array:Array = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

var somePerson:Person = new Person("Tom", 30);

Next you'll add a special function called a constructor function.

NOTE : The following exercise is part of Example: Writing custom classes. If you do not wish to progress through the example, you can download the class files from www.helpexamples.com/flash/learnas/classes/.

To add the constructor functions to your class files:

  1. Open the ClassA.as class file in the Flash authoring tool.

  2. Modify the existing class file so it matches the following code (the changes to make appear in boldface):

    class com.macromedia.utils.ClassA {

    function ClassA() {

    trace("ClassA constructor");

    }

    }

    The previous code defines a constructor method for the ClassA class. This constructor traces a simple string to the Output panel, which will let you know when a new instance of the class has been created.

  3. Open the ClassB.as class file in the Flash authoring tool.

  4. Modify the class file so it matches the following code (the changes to make appear in boldface):

    class com.macromedia.utils.ClassB {

    function ClassB() {

    trace("ClassB constructor");

    }

    }

  5. Save both ActionScript files before you proceed.

 

Adding methods and properties

TOP

To create the properties for the ClassA and ClassB classes, use the var keyword to define variables.

NOTE : The following three exercises are part of Example: Writing custom classes. If you do not wish to progress through the example, you can download the class files from

www.helpexamples.com/flash/learnas/classes/.

To add properties to the ClassA and ClassB classes:

  1. Open ClassA.as and ClassB.as in the Flash authoring tool.

  2. Modify the ClassA.as ActionScript file to match the following code (the changes to make appear in boldface):

    class com.macromedia.utils.ClassA {

    static var _className:String;

    function ClassA() {

    trace("ClassA constructor");

    }

    }

    The previous block of code adds a single new static variable, _className, which contains the name of the current class.

  3. Modify the ClassB class and add the static variable so it is similar to the previous code.

  4. Save both ActionScript files before you proceed.

TIP : By convention, class properties are defined at the top of the class body. Defining them at the top makes the code easier to understand, but isn't required.

You use the post-colon syntax (for example, var username:String and var age:Number) in the variable declarations. This is an example of strict data typing. When you type a variable using the var variableName:variableType format, the ActionScript compiler ensures that any values assigned to that variable match the specified type. If the correct data type is not used in the FLA file importing this class, the compiler throws an error.

A class's members consist of properties (variable declarations) and methods (function definitions). You must declare and define all properties and methods inside the class body (the curly braces [{}]); otherwise, an error occurs during compilation.

To add methods to the ClassA and ClassB classes:

  1. Open ClassA.as and ClassB.as in the Flash authoring tool.

  2. Modify the ClassA class file so it matches the following code (the changes to make appear in boldface):

    class com.macromedia.utils.ClassA {

    static var _className:String;

    function ClassA() {

    trace("ClassA constructor");

    }

    function doSomething():Void {

    trace("ClassA - doSomething()");

    }

    }

    The block of code in boldface creates a new method in the class, which traces a string to the Output panel.

  3. In ClassA.as, select Tools > Check Syntax to check the syntax of your ActionScript file.

    If any errors are reported in the Output panel, compare the ActionScript in your script to the complete code written in the previous step. If you cannot fix the code errors, copy and paste the complete code into the Script window before you proceed.

  4. Check the syntax of ClassB.as as you did in ClassA.as.

    If any errors appear in the Output panel, copy and paste the complete code into the Script window before you proceed:

    class com.macromedia.utils.ClassB {

    static var _className:String;

    function ClassB() {

    trace("ClassB constructor");

    }

    function doSomething():Void {

    trace("ClassB - doSomething()");

    }

    }

  5. Save both ActionScript files before you proceed.

You can initialize properties inline--that is, when you declare them--with default values, as shown in the following example:

class Person {

var age:Number = 50;

var username:String = "John Doe";

}

When you initialize properties inline, the expression on the right side of an assignment must be a compile-time constant. That is, the expression cannot refer to anything that is set or defined at runtime. Compile-time constants include string literals, numbers, Boolean values, null, and undefined, as well as constructor functions for the following top-level classes: Array, Boolean, Number, Object, and String.

To initialize properties inline:

  1. Open ClassA.as and ClassB.as in the Flash authoring tool.

  2. Modify the ClassA class file so the code matches the following ActionScript (the changes to make appear in boldface):

    class com.macromedia.utils.ClassA {

    static var _className:String = "ClassA";

    function ClassA() {

    trace("ClassA constructor");

    }

    function doSomething():Void {

    trace("ClassA - doSomething()");

    }

    }

    The only difference between the existing class file and the previous block of code is there is now a value defined for the static _className variable, "ClassA".

  3. Modify the ClassB class file and add the inline property, changing the value to "ClassB".

  4. Save both ActionScript files before you proceed.

This rule applies only to instance variables (variables that are copied into each instance of a class), not class variables (variables that belong to the class).

NOTE : When you initialize arrays inline, only one array is created for all instances of the class.

 

Controlling member access in your classes

TOP

By default, any property or method of a class can be accessed by any other class: all members of a class are public by default. However, in some cases you might want to protect data or methods of a class from access by other classes. You need to make those members private (available only to the class that declares or defines them).

You specify public or private members using the public or private member attribute. For example, the following code declares a private variable (a property) and a private method (a function). The following class (LoginClass) defines a private property named userName and a private method named getUserName():

class LoginClass {

private var userName:String;

private function getUserName():String {

return this.userName;

}

// Constructor:

public function LoginClass(user:String) {

this.userName = user;

}

}

Private members (properties and methods) are accessible only to the class that defines those members and to subclasses of that original class. Instances of the original class, or instances of subclasses of that class, cannot access privately declared properties and methods; that is, private members are accessible only within class definitions, not at the instance level. In the following example, you change member access in your class files.

NOTE : This exercise is part of Example: Writing custom classes. If you do not wish to progress through the example, you can download the class files from
www.helpexamples.com/flash/learnas/classes/.

To control member access:

  1. Open ClassA.as and ClassB.as in the Flash authoring tool.

  2. Modify the ClassA.as ActionScript file so its contents match the following ActionScript (the changes to make appear in boldface):

    class com.macromedia.utils.ClassA {

    private static var _className:String = "ClassA";

    public function ClassA() {

    trace("ClassA constructor");

    }

    public function doSomething():Void {

    trace("ClassA - doSomething()");

    }

    }

    This previous code sets both methods (the ClassA constructor and the doSomething() method) as public, meaning that they can be accessed by external scripts. The static _className variable is set as private, meaning the variable can be accessed only from within the class and not from external scripts.

  3. Modify the ClassB.as ActionScript file and add the same method and property access as the ClassA class.

  4. Save both ActionScript files before you proceed.

An instance of ClassA or ClassB cannot access the private members. For example, the following code, added to Frame 1 of the Timeline in a FLA file, would result in a compiler error indicating that the method is private and can't be accessed:

import com.macromedia.utils.ClassA;

var a:ClassA = new ClassA();

trace(a._className); // Error. The member is private and cannot be accessed.

Member access control is a compile-time-only feature; at runtime, Flash Player does not distinguish between private or public members.

 

Documenting the classes

TOP

Using comments in your classes and interfaces is an important part of documenting them for other users. For example, you might want to distribute your class files into the Flash community, or you might be working with a team of designers or developers who will use your class files in their work or as part of a project you're working on. Documentation helps other users understand the purpose and origins of the class.

There are two kinds of comments in a typical class or interface file: documentation comments and implementation comments. You use documentation comments to describe the code's specifications, but not the implementation. You use implementation comments to comment out code or to comment on the implementation of particular sections of code. The two kinds of comments use slightly different delimiters. Documentation comments are delimited with /** and */, and implementation comments are delimited with /* and */.

NOTE :Documentation comments are not a language construct in ActionScript 2.0. However, they are a common way of structuring comments in a class file that you can use in your AS files.
Use documentation comments to describe interfaces, classes, methods, and constructors. Include one documentation comment per class, interface, or member, and place it directly before the declaration.

If you have to document additional information that does not fit into the documentation comments, use implementation comments (in the format of block comments or single-line comments, as described in About comments). Implementation comments, if you add them, directly follow the declaration.

NOTE : Do not include comments that do not directly relate to the class being read. For example, do not include comments that describe the corresponding package.

NOTE : The following exercise is part of Example: Writing custom classes. If you do not wish to progress through the example, you can download the class files from

www.helpexamples.com/flash/learnas/classes/.

To document your class files:

  1. Open ClassA.as and ClassB.as in the Flash authoring tool.

  2. Modify the ClassA class file and add the new code to the top of the class file (the changes to make appear in boldface):

    /**

    ClassA class

    version 1.1

    6/21/2005

    copyright Macromedia, Inc.

    */

    class com.macromedia.utils.ClassA {

    private static var _className:String = "ClassA";

    public function ClassA() {

    trace("ClassA constructor");

    }

    public function doSomething():Void {

    trace("ClassA - doSomething()");

    }

    }

    The code above added a comment to the top of the class file. It's always a good idea to add comments to your ActionScript and Flash files so that you can add useful information such as the author of the class, date last modified, copyright information, or any potential issues/bugs that may be present in the file.

  3. Add a similar comment to the top of the ClassB.as ActionScript file, changing the class name and any other information as you see fit.

  4. Save both ActionScript files before you proceed.

You might also add the block, single-line, or trailing comments within the class's code.

 

Importing classes and packages

TOP

To reference a class in another script, you must prefix the class name with the class's package name. The combination of a class's name and its package path is the class's fully qualified class name. If a class resides in a top-level classpath directory--not in a subdirectory in the classpath directory--then its class name is also its fully qualified class name.

To specify package paths, use dot (.) notation to separate package directory names. Package paths are hierarchical; that is, each dot represents a nested directory. For example, suppose you create a class named ClassName that resides in a com/macromedia/docs/learnAs2 package in your classpath. To create an instance of that class, you could specify the fully qualified class name.

You can also use the fully qualified class name to type your variables, as shown in the following example:

var myInstance:com.macromedia.docs.learnAs2.ClassName = new com.macromedia.docs.learnAs2.ClassName();

You can use the import statement to import packages into a script, which lets you use a class's abbreviated name rather than its fully qualified name. You can also use the wildcard character (*) to import all the classes in a package. If you use the wildcard character, you don't need to use the fully qualified class name each time you use the class.

import com.macromedia.docs.learnAs2.util.UserClass;

Later, in the same script, you could reference that class by its abbreviated name, as shown in the following example:

var myUser:UserClass = new UserClass();

You can use the wildcard character (*) to import all the classes in a given package. Suppose you have a package named com.macromedia.utils that contains two ActionScript class files, ClassA.as and ClassB.as. In another script, you could import both classes in that package using the wildcard character, as shown in the following code:

import com.macromedia.utils.*;

The following example shows that you can then reference either of the classes directly in the same script:

var myA:ClassA = new ClassA();

var myB:ClassB = new ClassB();

The import statement applies only to the current script (frame or object) in which it's called. If an imported class is not used in a script, the class is not included in the resulting SWF file's bytecode, and the class isn't available to any SWF files that the FLA file containing the import statement might load.

To import a class or package:

  1. Open the file called package_test.fla.

  2. Type the following code into the Script window:

    import com.macromedia.utils.*;

    var a = new ClassA(); // ClassA constructor

    var b = new ClassB(); // ClassB constructor

    The previous block of code begins by importing each of the classes within the com.macromedia.utils package by using the wildcard (*) character. Next, you create a new instance of the ClassA class, which causes the constructor method to trace a message to the Output panel. An instance of the ClassB class is also created, which sends debugging messages to the Output panel.

  3. Save your changes to the Flash document before you proceed.

 

Compiling and exporting classes

TOP

By default, classes used by a SWF file are packaged and exported in the SWF file's first frame. You can also specify a different frame where your classes are packaged and exported. This is useful, for example, if a SWF file uses many classes that require a long time to download (such as components). If the classes are exported in the first frame, the user has to wait until all the class code has downloaded before that frame appears. By specifying a later frame in the timeline, you could display a short-loading animation in the first few frames of the timeline while the class code in the later frame downloads.
To specify the export frame for classes for a Flash document:
Select File > New and then select Flash Document. Save the new document as exportClasses.fla.
Rename the default layer to content, drag a ProgressBar component from the Components panel to the Stage, and give it an instance name of my_pb.
Create a new layer, drag it above the content layer, and rename it actions.
Add the following ActionScript code to Frame 1 of the actions layer on the main Timeline:
my_pb.indeterminate = true;

Create a new keyframe on Frame 2 of the actions layer and add the following ActionScript code:
var classesFrame:Number = 10;
if (_framesloaded < classesFrame) {
trace(this.getBytesLoaded() + " of " + this.getBytesTotal() + " bytes loaded");
gotoAndPlay(1);
} else {
gotoAndStop(classesFrame);
}

Create a new keyframe on Frame 10 of the actions layer and add the following ActionScript:
stop();

Create a new keyframe on Frame 10 of the content layer and drag several components onto the Stage.
Right-click each component (except the ProgressBar) in the Library panel and select Linkage from the context menu to launch the Linkage Properties dialog box.
In the Linkage Properties dialog box, make sure that Export for ActionScript is selected, deselect the Export in First Frame check box, and click OK.
Select File > Publish Settings.
In the Publish Settings dialog box, select the Flash tab.
Click the Settings button next to the ActionScript version pop-up menu to open the ActionScript Settings dialog box.
In the Export Frame for Classes text box, enter the number of the frame where you want to export your class code (Frame 10).
If the frame specified does not exist in the timeline, you get an error message when you publish your SWF file.
Click OK to close the ActionScript Settings dialog box, and then click OK to close the Publish Settings dialog box.
Select Control > Test Movie to test the Flash document. If the Components load too quickly, select View > Simulate Download from the SWF file. Flash simulates downloading the Flash document at a lower speed, which allows you to see the progress bar component animate as the class files download.
 

 

Assigning a class to symbols in Flash

TOP

You can also assign a class to symbols that you might use in a Flash file, such as a movie clip object on the Stage.

To assign a class to a movie clip symbol:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Select File > Save As, name the file Animal.as, and save the file on your hard disk.

  3. Type the following code into the Script window:

    class Animal {

    public function Animal() {

    trace("Animal::constructor");

    }

    }

    This ActionScript creates a new class called Animal that has a constructor method that traces a string to the Output panel.

  4. Save your changes to the ActionScript file.

  5. Select File > New and then select Flash Document to create a new FLA file, and then click OK.

  6. Select File > Save As, name the file animal_test.fla, and save the file to the same folder as the Animal.as file you created in step 2.

  7. Select Insert > New Symbol to launch the Create New Symbol dialog box.

  8. Enter a symbol name of animal, and select the Movie Clip option.

  9. Click the Advanced button in the lower-right corner of the Create New Symbol dialog box to enable more options.

    The Advanced button is available when you are in the basic mode of the Create New Symbol dialog box.

  10. Click the Export for ActionScript check box in the Linkage section.

    Enabling this option allows you to dynamically attach instances of this symbol to your Flash documents during runtime.

  11. Enter an identifier value of animal_id, and set the ActionScript 2.0 Class to Animal (to match the class name specified in step 3).

  12. Select the Export in First Frame check box and click OK to apply your changes and close the dialog box.

  13. Save the Flash document and select Control > Test Movie.

    The Output panel displays the text from your Animal class's constructor function.

 

About the conditional operator and alternative syntax

TOP

By default, classes used by a SWF file are packaged and exported in the SWF file's first frame. You can also specify a different frame where your classes are packaged and exported. This is useful, for example, if a SWF file uses many classes that require a long time to download (such as components). If the classes are exported in the first frame, the user has to wait until all the class code has downloaded before that frame appears. By specifying a later frame in the timeline, you could display a short-loading animation in the first few frames of the timeline while the class code in the later frame downloads.

To specify the export frame for classes for a Flash document:

  1. Select File > New and then select Flash Document. Save the new document as exportClasses.fla.

  2. Rename the default layer to content, drag a ProgressBar component from the Components panel to the Stage, and give it an instance name of my_pb.

  3. Create a new layer, drag it above the content layer, and rename it actions.

  4. Add the following ActionScript code to Frame 1 of the actions layer on the main Timeline:

    my_pb.indeterminate = true;

  5. Create a new keyframe on Frame 2 of the actions layer and add the following ActionScript code:

    var classesFrame:Number = 10;

    if (_framesloaded < classesFrame) {

    trace(this.getBytesLoaded() + " of " + this.getBytesTotal() + " bytes loaded");

    gotoAndPlay(1);

    } else {

    gotoAndStop(classesFrame);

    }

  6. Create a new keyframe on Frame 10 of the actions layer and add the following ActionScript:

    stop();

  7. Create a new keyframe on Frame 10 of the content layer and drag several components onto the Stage.
    Right-click each component (except the ProgressBar) in the Library panel and select Linkage from the context menu to launch the Linkage Properties dialog box.
    In the Linkage Properties dialog box, make sure that Export for ActionScript is selected, deselect the Export in First Frame check box, and click OK.

  8. Select File > Publish Settings.

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

  10. Click the Settings button next to the ActionScript version pop-up menu to open the ActionScript Settings dialog box.

  11. In the Export Frame for Classes text box, enter the number of the frame where you want to export your class code (Frame 10).

    If the frame specified does not exist in the timeline, you get an error message when you publish your SWF file.

  12. Click OK to close the ActionScript Settings dialog box, and then click OK to close the Publish Settings dialog box.

  13. Select Control > Test Movie to test the Flash document. If the Components load too quickly, select View > Simulate Download from the SWF file. Flash simulates downloading the Flash document at a lower speed, which allows you to see the progress bar component animate as the class files download.

 

Using ASO files

TOP

During compilation, Flash sometimes creates files with .aso extensions in the /aso subdirectory of the default global classpath directory (see About setting and modifying the classpath). The .aso extension stands for ActionScript object (ASO). For each ActionScript 2.0 file that is implicitly or explicitly imported and successfully compiled, Flash generates an ASO file. The file contains the bytecode that's produced from the associated ActionScript (AS) file. Therefore, these files contain the compiled form (the bytecode) of a class file.

Flash needs to regenerate an ASO file only when the following scenarios occur:

  • The corresponding AS file has been modified.

  • ActionScript files that contain definitions imported or used by the corresponding ActionScript file have been modified.

  • ActionScript files included by the corresponding ActionScript file have been modified.

The compiler creates ASO files for caching purposes. You might notice that your first compilation is slower than subsequent compilations. This is because only the AS files that have changed are recompiled into ASO files. For unchanged AS files, the compiler reads the already-compiled bytecode directly out of the ASO file instead of recompiling the AS file.

The ASO file format is an intermediate format developed for internal use only. It is not a documented file format and is not intended to be redistributed.

If you experience problems in which Flash appears to be compiling older versions of a file you have edited, delete the ASO files and then recompile. If you plan to delete ASO files, delete them when Flash is not performing other operations, such as checking syntax or exporting SWFs.

To delete ASO files:

If you are editing a FLA file, and you want to delete an ASO file, select one of the following in the authoring environment:

  • Select Control > Delete ASO Files to delete ASO files and continue editing.

  • Select Control > Delete ASO Files and Test Movie to delete ASO files and test the application.

If you are editing an ActionScript document in the Script window:

  • Select Control > Delete ASO Files to delete ASO files and continue editing.

  • Select Control > Delete ASO Files and Test Project to delete ASO files and then test the application.

There is a limit to how much code you can place in a single class: the bytecode for a class definition in an exported SWF file cannot be larger than 32,767 bytes. If the bytecode is larger than that limit, a warning message appears.

You can't predict the size of the bytecode representation of a given class, but classes up to 1,500 lines usually don't go over the limit.

If your class goes over the limit, move some of the code into another class. In general, it is good OOP practice to keep classes relatively short.

 

Understanding classes and scope

TOP

When you move ActionScript code into classes, you might have to change how you use the this keyword. For example, if you have a class method that uses a callback function (such as the LoadVars class's onLoad() method), it can be difficult to know whether the this keyword refers to the class or to the LoadVars object. In this situation, it might be necessary to create a pointer to the current class, as the next example shows.

To understand scope and external class files:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Type or paste the following code into the Script window:

    /**

    Product class

    Product.as

    */

    class Product {

    private var productsXml:XML;

    // constructor

    // targetXmlStr - string, contains the path to an XML file

    function Product(targetXmlStr:String) {

    /* Create a local reference to the current class.

    Even if you are within the XML's onLoad event handler, you

    can reference the current class instead of only the XML packet.

    */

    var thisObj:Product = this;

    // Create a local variable, which is used to load the XML file.

    var prodXml:XML = new XML();

    prodXml.ignoreWhite = true;

    prodXml.onLoad = function(success:Boolean) {

    if (success) {

    /* If the XML successfully loads and parses,

    set the class's productsXml variable to the parsed

    XML document and call the init function.

    */

    thisObj.productsXml = this;

    thisObj.init();

    } else {

    /* There was an error loading the XML file. */

    trace("error loading XML");

    }

    };

    // Begin loading the XML document.

    prodXml.load(targetXmlStr);

    }

    public function init():Void {

    // Display the XML packet.

    trace(this.productsXml);

    }

    }

    Because you are trying to reference the private member variable within an onLoad handler, the this keyword actually refers to the prodXml instance and not the Product class, which you might expect. For this reason, you must create a pointer to the local class file so that you can directly reference the class from the onLoad handler. You can now use this class with a Flash document.

  3. Save the previous ActionScript code as Product.as.

  4. Create a new Flash document named testProduct.fla in the same directory.

  5. Select Frame 1 of the main Timeline.

  6. Type the following ActionScript into the Actions panel:

    var myProduct:Product = new Product("http://www.helpexamples.com/crossdomain.xml");

  7. Select Control > Test Movie to test this code in the test environment.

    The contents of the specified XML document appear in the Output panel.

Another type of scope you encounter when working with these classes is static variables and static functions. The static keyword specifies that a variable or function is created only once per class rather than being created in every instance of that class. You can access a static class member without creating an instance of the class by using the syntax someClassName.username.

Another benefit of static variables is that static variables don't lose their values after the variable's scope has ended. The following example demonstrates how you can use the static keyword to create a counter that tracks how many instances of the class Flash has created. Because the numInstances variable is static, the variable is created only once for the entire class, not for every single instance.

To use the static keyword:

  1. Select File > New and then select ActionScript File, and then click OK.

  2. Type the following code into the Script window:

    class User {

    private static var numInstances:Number = 0;

    public function User() {

    User.numInstances++;

    }

    public static function get instances():Number {

    return User.numInstances;

    }

    }

    The previous code defines a User class that tracks the number of times the constructor has been called. A private, static variable (User.numInstances) is incremented within the constructor method.

  3. Save the document as User.as.

  4. Select File > New and then select Flash Document to create a new FLA file, and save the FLA file in the same directory as User.as.

  5. Type the following ActionScript code in Frame 1 of the Timeline:

    trace(User.instances); // 0

    var user1:User = new User();

    trace(User.instances); // 1

    var user2:User = new User();

    trace(User.instances); // 2

    The first line of code calls the static instances() getter method, which returns the value of the private static numInstances variable. The rest of the code creates new instances of the User class and displays the current value returned by the instances() getter method.

  6. Select Control > Test Movie to test the documents.

 

About creating a new instance of a built-in class

TOP

To create an instance of an ActionScript class, use the new operator to invoke the class's constructor function. The constructor function always has the same name as the class, and returns an instance of the class, which you typically assign to a variable.

For example, the following code creates a new Sound object:

var song_sound:Sound = new Sound();

In some cases, you don't need to create an instance of a class to use its properties and methods.

 

Accessing built-in object properties

TOP

Use the dot (.) operator to access the value of a property in an object. Put the name of the object on the left side of the dot, and put the name of the property on the right side. For example, in the following statement, my_obj is the object and firstName is the property:

my_obj.firstName

The following code creates a new Array object and then shows its length property:

var my_array:Array = new Array("apples", "oranges", "bananas");

trace(my_array.length); // 3

You can also use the array access operator ([]) to access the properties of an object, such as using the array access operator for debugging purposes. The following example loops over an object to display each of its properties.

To loop over the contents of an object:

  1. Create a new Flash document and save it as forin.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var results:Object = {firstName:"Tommy", lastName:"G", age:7, avg:0.336, b:"R", t:"L"};

    for (var i:String in results) {

    trace("the value of [" + i + "] is: " + results[i]);

    }

    The previous code defines a new Object named results and defines values for firstName, lastName, age, avg, b, and t. A for..in loop traces each property in the results object and traces their value to the Output panel.

  3. Select Control > Test movie to test the Flash document.

 

About calling built-in object methods

TOP

You call an object's method by using the dot (.) operator followed by the method. For example, the following code creates a new Sound object and calls its setVolume() method:

var my_sound:Sound = new Sound(this);

my_sound.setVolume(50);

 

About class (static) members

TOP

Some built-in ActionScript classes have class members (static members). Class members (properties and methods) are accessed or invoked on the class name, not on an instance of the class. Therefore, you don't create an instance of the class to use those properties and methods.

For example, all the properties of the Math class are static. The following code invokes the max() method of the Math class to determine the larger of two numbers:

var largerNumber:Number = Math.max(10, 20);

trace(largerNumber); // 20

 

Excluding classes

TOP

To reduce the size of a SWF file, you might want to exclude classes from compilation but still be able to access and use them for type checking. For example, you might want to do this if you are developing an application that uses multiple SWF files or shared libraries, especially those that access many of the same classes. Excluding classes helps you avoid duplicating classes in those files.

For more information on excluding classes, see the following topics:

  • Preloading class files

To exclude classes from compilation:

  1. Create a new XML file.

  2. Name the XML file FLA_filename_exclude.xml, where FLA_filename is the name of your FLA file without the extension.

  3. For example, if your FLA file is sellStocks.fla, the XML filename must be sellStocks_exclude.xml.

  4. Save the file in the same directory as the FLA file.

  5. Place the following tags in the XML file:

    <excludeAssets>

    <asset name="className1" />

    <asset name="className2" />

    </excludeAssets>

    The values you specify for the name attributes in the <asset> tags are the names of classes you want to exclude from the SWF file. Add as many as you require for your application. For example, the following XML file excludes the mx.core.UIObject and mx.screens.Slide classes from the SWF file:

    <excludeAssets>

    <asset name="mx.core.UIObject" />

    <asset name="mx.screens.Slide" />

    </excludeAssets>

 

Preloading class files

TOP

This section describes some of the methodologies for preloading and exporting classes in Flash 8 (including the classes that components in version 2 of the Macromedia Component Architecture use). Preloading involves loading some of the data for a SWF file before the user starts interacting with it. Flash imports classes on the first frame of a SWF file when you use external classes, and this data is the first element to load into a SWF file. It is similar for the component classes, because the framework for components also loads into the first frame of a SWF file. When you build large applications, the loading time can be lengthy when you must import data, so you must deal with this data intelligently, as the following procedures show.

Because the classes are the first data to load, you might have problems creating a progress bar or loading animation if the classes load before the progress bar, because you probably want the progress bar to reflect the loading progress of all data (including classes). Therefore, you want to load the classes after other parts of the SWF file, but before you use components.
The following procedure shows you how to change the frame in which classes load into a SWF file.

To select a different frame for the classes to load into a SWF file:

  1. Select File > Publish Settings.

  2. Select the Flash tab, and click the Settings button.

  3. In the Export Frame for Classes text box, type the number of a new frame to determine when to load the classes.

  4. Click OK.

You cannot use any classes until the playhead reaches the frame you choose to load them into. For example, version 2 components require classes for their functionality, so you must load components after the Export frame for ActionScript 2.0 classes. If you export for Frame 3, you cannot use anything from those classes until the playhead reaches Frame 3 and loads the data.

If you want to preload a file that uses classes, such as version 2 component classes, you must preload the components in the SWF file. To accomplish this, you must set your components to export for a different frame in the SWF file. By default, the UI components export in Frame 1 of the SWF file, so make sure that you deselect Export in First Frame from the component's Linkage dialog box.

If components do not load on the first frame, you can create a custom progress bar for the first frame of the SWF file. Do not reference any components in your ActionScript or include any components on the Stage until you load the classes for the frame you specified in the Export Frame for Classes text box.

CAUTION : You must export components after the ActionScript classes that they use.

 

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