23 November 2010
Beginning
Any time you're writing ActionScript code you're probably using object-oriented programming: creating object instances, reading or setting values of properties, calling methods to perform actions, and responding to events dispatched by objects. However, in addition to using the built-in objects, you can also define your own object types (known as classes). As your ActionScript projects move beyond simple functionality, using your own classes can make programming easier by allowing you to organize your ActionScript, group related functionality together, and hide details when you don't need to see them.
Before you create a class, you'll want to spend some time thinking about the design of your application and how you should structure your classes. For some ideas on how to organize your classes, see "Creating your own classes" in Learning ActionScript 3.0.
Once you have a design plan for your class, or at least some idea of what information it will need to keep track of and what actions it will need to carry out, the actual syntax of writing a class is fairly straightforward.
In this Quick Start, you'll create a small ActionScript class called the Greeter class. The structure of the Greeter class is as follows (the full code can be found in the example at the end of this Quick Start):
package com.example.quickstart
{
public class Greeter
{
// ------- Constructor -------
public function Greeter(initialName:String = "")
{
// set the name value, if specified
}
// ------- Properties -------
public var name:String;
// ------- Methods -------
public function sayHello():String
{
// create the greeting text and pass it as the return value
}
}
}
The following sections detail the steps you'll go through to create and use your own ActionScript class.
An ActionScript 3.0 class is written as a text document, separate from a Flash FLA or Flex MXML file that may use it. The class file needs to have the same name as the class, with a .as extension. The class file should be contained in a hierarchy of folders matching the package structure of your class. In this example, we're creating the Greeter class, so it will be saved in a file named Greeter.as. The complete class name including package is "com.example.quickstart.Greeter" (the Greeter class is contained in the "com.example.quickstart" package), so the Greeter.as file must be saved in a folder structure like this: "/com/example/quickstart/." The "com" folder can be contained in the root folder of your application, or in a folder that's part of the ActionScript classpath for your application.
To create the class file for the Greeter class:
You use the class statement to define the name of a class. A class must be specified as "public" in order for other code to create instances of that class (essentially, except in a few special circumstances all ActionScript 3.0 classes must be public). The complete statement, then, is public class ClassName. That statement is then followed by a pair of curly braces that surround the class's contents.
The class statement, in turn, must be enclosed in a package statement, indicating the name of the package in which your class is found. The syntax is similar to the class statement syntax: the word package followed by the package name, then a pair of curly braces surrounding the package contents (the single class statement plus any import statements that are necessary).
To add the class and package statements to the Greeter class:
package com.example.quickstart
{
public class Greeter
{
// class contents (methods and properties) will go here
}
}
This code includes the package statement (package com.example.quickstart) with its set of curly braces, inside of which is the class statement (public class Greeter) with its set of curly braces.
You define a property in a class using the var statement within the class body. The syntax is the same as what you use to declare any variable, except that you add the public modifier (in the same way you used it with the class statement).
To define the name property in the Greeter class:
class statement, add a blank line and enter the following code:public var name:String;
This line of code defines the name property, which holds String values. You can optionally specify a default value for the property in the same way that you specify an initial value for a variable (for example, public var name:String = "Fred";). However, in this Quick Start you'll set the initial value in the constructor method instead.
Note that you can also define private properties by using the modifier private instead of public, like this:
private var secretValue:Number;
Private properties are essentially variables that can be accessed by any of the code within the class definition, but are not available outside the class definition.
You define a method in your class using the same syntax that's used to define a function, with the addition of an access modifier (such as public or private). A method defnition consists of the following elements:
public or private)functionvoid if the method doesn't return a value) To create the sayHello() method, which doesn't accept any parameters and returns a String value:
class statement, enter the following lines of code:public function sayHello():String
{
var result:String;
if (name != null && name.length > 0)
{
result = "Hello there, " + name + ".";
}
else
{
result = "Hello there, anonymous.";
}
return result;
}
The constructor method is a special method that is called as part of the process of creating an instance of a class. You can use the constructor to specify initial values for properties or perform other setup details. As part of the special nature of constructor methods, when you define a constructor the name of the method must match the class name exactly, the method must be defined as public, and you do not specify a return value data type (or void).
To create the constructor method for the Greeter class:
public function Greeter(initialName:String = "")
{
name = initialName;
}
This code defines a constructor that optionally accepts a single String parameter. If a value is passed for that parameter, the value is assigned to the name property. Otherwise the name property is set to "" (an empty string) because that is the default value for the method parameter.
If you don't define a constructor method in your class (for example, if you don't need to perform any setup operations), the compiler will automatically create an empty constructor (one with no parameters and no statements) for your class.
There are a few more class elements that you can define. The process of creating these elements is more involved than creating methods and properties, so they are not covered in detail in this Quick Start:
You can create and use instances of your class just as you do with any other ActionScript class. First you must use the import statement with the package and name of your class, to tell the compiler where to look for your class. For the Greeter class, the import statement looks like this:
import com.example.quickstart.Greeter;
Once you've added the import statement, you can use your class like any other class. For instance, you can declare a variable whose data type is your class, and create an instance of the class to store in the variable:
var michaelGreeter:Greeter = new Greeter("Michael");
You can also assign values to the instance's properties and call its methods:
michaelGreeter.name = "Mike"
trace(michaelGreeter.sayHello());
The following example creates an instance of the Greeter class, sets the name property to "Steve", then calls the sayHello() method and writes the resulting greeting to a text field (Flash) or Text component (Flex) on the screen.
This example consists of two parts: the Greeter class in the Greeter.as file (the file you've been building in this Quick Start) and an application file (a Flash FLA or Flex MXML file) that creates and uses an instance of the Greeter class. The following code block shows a complete version of the Greeter class. Instructions for creating the Flash and Flex versions of the example application file follow.
package com.example.quickstart
{
public class Greeter
{
public function Greeter(initialName:String = "")
{
name = initialName;
}
public var name:String;
public function sayHello():String
{
var result:String;
if (name != null && name.length > 0)
{
result = "Hello there, " + name + ".";
}
else
{
result = "Hello there, anonymous.";
}
return result;
}
}
}
import com.example.quickstart.Greeter;
// Create a Greeter instance with the initial name "Steve"
var myGreeter:Greeter = new Greeter("Steve");
// Say hello to Steve
output.text = myGreeter.sayHello();
// Move the cursor to the next line
output.text += "\n";
// Set the Greeter instance's name to "Harold"
myGreeter.name = "Harold";
// Say hello to Harold
output.text += myGreeter.sayHello();
mx:Application tag: initialize="initApp();"mx:Application tag should now look like this:<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="initApp();">
</mx:Application>
id of "output" inside the <mx:Application> tag. Set its width attribute to "100%" and its textAlign attribute to "center". The code should now look like this:<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="initApp();">
<mx:Text id="output" width="100%" textAlign="center" />
</mx:Application>
mx:Script block to the application MXML file, so it will look like this:<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="initApp();">
<mx:Script>
<![CDATA[
import com.example.quickstart.Greeter;
private function initApp():void
{
// Create a Greeter instance with the initial name "Steve"
var myGreeter:Greeter = new Greeter("Steve");
// Say hello to Steve
output.text = myGreeter.sayHello();
// Move the cursor to the next line
output.text += "\n";
// Set the Greeter instance's name to "Harold"
myGreeter.name = "Harold";
// Say hello to Harold
output.text += myGreeter.sayHello();
}
]]>
</mx:Script>
<mx:Text id="output" width="100%" textAlign="center" />
</mx:Application>
Result
To download the Flash source files for this example, click here or right-click the Flash application and select Download Source from the context menu.
To download the Flex source files for this example, click here.
This article was adapted from the section "Creating your own classes" in Programming ActionScript 3.0. For more information about this topic, see that section, as well as the following resources:
Related Flash Quick Starts