Using classes: a simple example

If you're new to object-oriented programming, it might help to get an overview of how you create and use classes in Flash, the overall workflow, before getting into details. Creating and using a class involves, minimally, the following steps:

This section walks you through these steps to create and use a class. You can find completed versions of the files you'll create in your Flash install directory (. Also discussed in this section is a new feature in ActionScript 2 called data typing, which lets you specify the data type for a variable, function parameter, or function return type.

This section only discusses classes, but the general workflow is same for using interfaces, as well. For more information see Creating and using interfaces.

Creating the class file

To create a class, you must first create an external ActionScript (AS) file. Classes (and interfaces) can only be defined in external script files. For example, you can't define a class in a script attached to frame or button in a Flash document (FLA). To create an external AS file, use the ActionScript editor included with Flash, or your preferred code or text editor.

In the steps below you'll create class called Person that contains two properties (age and name) and a single method (showInfo()) that displays the values of those properties in the Output panel.

To create the class file:

  1. Create a new folder on your hard disk and name it PersonFiles. This folder will contain all the files for this project.
  2. In Flash, choose File > New to open the New Document dialog, select ActionScript File from the list of file types, then click OK.
  3. The external ActionScript editor window opens with a blank file.

  4. Save the file as Person.as to the PersonClass folder.
  5. In the ActionScript editor window, enter the following code:
  6. class Person {
    }
    

    This is called the class declaration. In it's most basic form, a class declaration consists of the class keyword, followed the class name (Person, in this case), and then left and right curly braces ({}). Everything between the curly braces is called the class body and is where the class's properties and methods are defined.

    Also note that the name of the class (Person) matches the name of the AS file that contains it (Person.as). This is very important; if these two names don't match, the class won't compile.

  7. To create the properties for the Person class, use the var keyword to define two variables named age and name, as shown below.
  8. class Person {
    
    	var age:Number;
    	var name:String;
    
    }
    

By convention, class properties are defined at the top of the class body, which makes understanding the code easier, but this isn't required.

Notice the colon syntax (var age:Number and var name:String) used to in the variable declarations. This is a feature of ActionScript 2 called data typing. When you type a variable in this way (var variableName:variableType), the ActionScript 2 compiler makes sure that any values assigned to that variable match the specified type. While not required, typing your variables is good practice and can make debugging your scripts easier. For more information on data typing see .

  • Next you'll create the showInfo() method, which returns a pre-formatted string containing the values of the age and name properties. Add the showInfo() function definition to the class body, as shown below.
  • class Person {
    
    	var age:Number;
    	var name:String;
    
    	// Method to return property values
    	function showInfo():String {
    		return("Hello, my name is " + name + " and I'm " + age + " years old.");
    	}
    }
    

    Notice again the use of the (optional but encouraged) data typing in the function definition.

    function showInfo():String {...}
    

    In this case, what's being typed is the showInfo() function's return value (a string). The last way you can use data typing is to type function parameters, as shown in the next step.

  • The last bit of code you'll add in this section is a special function, called the constructor function. In object-oriented programming, the constructor function initializes each new instance of a class (as you'll see in the next section, Creating an instance of the Person class.)
  • The constructor function always has the same name as the class. For more information about constructor functions, see Constructor functions.

    class Person {
    
    	var age:Number;
    	var name:String;
    	
    	// Method to return property values
    	function showInfo():String {
    		return("Hello, my name is " + name + " and I'm " + age + " years old.");
    	}
    	
    	// Constructor function
    	function Person (myName:String, myAge:Number) {
    		name = myName;
    		age = myAge;
    	}
    }
    

    The Person() constructor function takes two parameters, myName and myAge, and assigns those parameters to the age and name properties. Notice, finally, that the two function parameters are strongly typed as String and Number, respectively.

  • Save the file as Person.as to the PersonFiles folder that you created in Step 1.
  • Again, note that the name of the ActionScript file (Person.as) matches the name of the class it contains (Person). This is required for the class to properly compile.To check your syntax, select Tools > Check Syntax, or press Control + T (Windows) or Command+T (Macintosh).
  • If any errors are reported in the Output panel, compare the code in the ActionScript editor to the final code in Step 6, above. If you can't fix the code errors, copy the code in the previous step from the Help panel, or from the completed AS class file (<path to installed file>), and paste it into the ActionScript editor, save, and check syntax again.

    Creating an instance of the Person class

    The next step is to create an instance of the Person class in another script, such as a frame script in a Flash (FLA) document or another AS script, and assign it to a variable. To create an instance of a custom object you use the new operator, just as you would when creating an instance of a built-in ActionScript class (like the XML or TextField objects).

    For example, the following code creates an instance of the Person class and assigns it to the variable newPerson.

    var newPerson = new Person("Nate", 32);
    

    This code invokes the Person class's constructor function, passing as parameters the values "Nate" and "32".

    To create an instance of the Person class in a Flash document:

    1. In Flash, choose File > New, select Flash Document from the list of document types, and click OK.
    2. Save the file as createPerson.fla in the PersonFiles folder you created previously.
    3. Select Layer 1 in the Timeline and open the Actions panel by pressing the F9 function key or choosing Windows > Development Panels > Actions.
    4. In the Actions panel enter the following code:
    5. var person_1 = new Person("Nate", 32);
      var person_2 = new Person("Jane", 28);
      trace(person_1.showInfo());
      trace(person_2.showInfo());
      

      The above creates a two instance of the Person class, person_1 and person_2, and then calls the showInfo() method on each instance.

    6. Save your work, then choose Control > Test Movie to test. You should see the following appear in the Output panel on separate lines.
    7. Hello, my name is Nate and I'm 32 years old.
      Hello, my name is Jane and I'm 28 years old.
      

    Where the compiler looks for classes

    When you create an instance of a class by calling it's constructor function, Flash looks for a AS file of the same name as the constructor in a set of predetermined folder locations. This group of folder locations is known collectively as the classpath. For more information about the classpath see Understanding the classpath.

    Now that you've gotten an overall idea about how you to create and use classes in your Flash documents, the rest of this chapter will explore classes and interfaces in more detail.