User Guide

Using classes: a simple example 251
Creating a class file
To create a class, you must first create an external ActionScript (AS) file. Classes (and interfaces)
can be defined only in external script files. You cant define a class in a script attached to a frame
or button in a Flash document (FLA file). To create an external AS file, use the ActionScript
editor included with Flash Professional or your preferred code or text editor.
Note: 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.
In the following steps, you’ll create a class called Person that contains two properties (age and
name) and a single method (getInfo()) that shows the values of those properties in the
Output panel.
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 (in Flash Professional 2004), you also need to tell
Flash how it can find the file. For real applications, you would add the directory in which you
store your application and class files to the Flash classpath. For information about classpaths, see
“Understanding the classpath” on page 268 and “Modifying the classpath” on page 270. For
information about organizing your project directories, see “Using packages” on page 260.
To create the class file:
1.
Create a directory on your hard disk, and name it PersonFiles. This directory will contain all
the files for this project.
2.
(Optional) In Flash, add the PersonFiles directory to the global classpath.
3.
Do one of the following:
Create a new file in your preferred text or code editor.
(Flash Professional only) Select File > New to open the New Document dialog box, select
ActionScript File from the list of file types, and click OK. The Script window opens with a
blank file.
4.
Save the file as Person.as in the PersonFiles directory.
5.
In the Script window, enter the following code (in this procedure, new code you type in each
step is
bold):
class Person {
}
This is called the class declaration. 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 classs
properties and methods are defined.
The name of the class (Person) must exactly match the name of the AS file that contains it
(Person.as). This is very important; if these two names dont match exactly, including
capitalization, the class wont compile.