User Guide

Creating and using classes 51
This code invokes the Person class’s constructor function, passing as parameters the values "Nate"
and 32.
The
newPerson variable is typed as a Person object. Typing your objects in this way enables the
compiler to ensure that you dont try to access properties or methods that arent defined in the
class. See “Strict data typing” on page 24. (The exception is if you declare the class to be dynamic
using the
dynamic keyword. See “Creating dynamic classes” on page 56.)
To create an instance of the Person class:
1.
Create a new file in your preferred text or code editor.
2.
Save the file as createPerson.as in the PersonFiles directory you created.
3.
Enter the following code:
var person_1:Person = new Person("Nate", 32);
var person_2:Person = new Person("Jane", 28);
trace(person_1.getInfo());
trace(person_2.getInfo());
This code creates two instances of the Person class, person_1 and person_2, and then calls the
getInfo() method on each instance.
You should now have a basic understanding of how to create and use classes in your scripts. The
rest of this chapter discusses classes and interfaces in more detail.
Creating and using classes
As discussed in “Using classes: a simple example” on page 48, a class consists of two parts: the
declaration and the body. The class declaration consists minimally of the
class statement,
followed by an identifier for the class name, then left and right curly braces ({}). Everything inside
the braces is the class body, as shown in the following example:
class className {
// class body
}
You can define classes only in AS 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. The class name must exactly match the name of the AS file
that contains it, including capitalization. In the following example, if you create a class called
Shape, the AS file that contains the class definition must be named Shape.as:
// In file Shape.as
class Shape {
// Shape class body
}
All AS class files that you create must be saved in one of the designated classpath directories—
directories where Flash looks for class definitions when compiling scripts—that is, in the same
directory where the FLA file that refers to the class is stored. For more information on including
AS files in Flex applications, see “Using ActionScript” in Developing Flex Applications.