Creating and using classes 161
Creating and using classes
As discussed previously, 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.
class className {
// class body
}
You can define classes only in ActionScript (AS) files. For example, you can’t define a class on a
frame script in a FLA file. Also, the specified class name must match the name of the AS file that
contains it. For 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. (See “Understanding
the classpath” on page 169.)
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.
Also, the class name must be fully qualified within the file in which it is declared; that is, it must
reflect the directory in which it is stored. For example, to create a class named RequiredClass that
is stored in the myClasses/education/curriculum directory, you must declare the class in the
RequiredClass.as file like this:
class myClasses.education.curriculum.RequiredClass {
}
For this reason, it’s good practice to plan your directory 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.
Creating properties and methods
A class’s members consist of properties (variable declarations) and methods (function
declarations). You must declare all properties and methods inside the class body (the curly braces);
otherwise, an error will occur during compilation.
Any variable declared within a class, but outside a function, is a property of the class. For
example, the Person class discussed earlier has two properties,
age and name, of type Number and
String, respectively.
class Person {
var age:Number;
var name:String;
}