Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Flash Developer Center /

Creating a simple ActionScript 3 class

by H. Paul Robertson

H. Paul Robertson

Content

  • Create the class file
  • Create the class and package statements
  • Add properties to the class
  • Add methods to the class
  • Add other class elements
  • Use your class in your application
  • Creating the example

Modified

23 November 2010

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScript Flash Professional CS5

Requirements

User level

Beginning

Required products

  • Flash Professional (Download trial)
  • Flash Builder (Download trial)

Sample files

  • asgreeter_flash_source.zip (13 KB)
  • asgreeter_flex_source.zip (2 KB)

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.

Create the class file

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:

  1. Open a new text document, in an ActionScript-specific program such as Flex Builder or Flash, in a general programming tool such as Dreamweaver, or in any program that allows you to work with plain text documents.
  2. Save the file as "Greeter.as" in a folder structure matching the following: "/com/example/quickstart/" where the "com" folder is in the root folder of your application.

Create the class and package statements

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:

  • In your ActionScript file, enter the following code:
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.

Add properties to the class

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:

  • In between the opening and closing curly braces of the 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.

Add methods to the class

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:

  • The access modifier (usually public or private)
  • The word function
  • The name of the function
  • Opening and closing parentheses containing definitions of any parameters that the method accepts
  • A colon, followed by the data type of the value returned by the method (or void if the method doesn't return a value)
  • Opening and closing curly braces, surrounding the statements that are performed by the method.

To create the sayHello() method, which doesn't accept any parameters and returns a String value:

  • Inside the opening and closing curly braces of the 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:

  • Between the opening and closing curly braces of the class statement, enter the following lines of code:
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.

Add other class elements

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:

  • Accessors are a special cross between a method and a property. When you write the code to define the class, you write the accessor like a method so you can perform multiple actions (rather than just reading or assigning a value, which is all you can do when you define a property). However, when you create an instance of your class, you treat the accessor like a property—using just the name to read or assign the value. For more information, see "Get and set accessor methods" in Learning ActionScript 3.0.
  • Events in ActionScript aren't defined using a specific syntax. Instead, you define events in your class by using the functionality of the EventDispatcher class to keep track of event listeners and notify them of events. For more on creating events in your own classes, see "Handling events" in the ActionScript 3.0 Developer's Guide.

Use your class in your application

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());

Creating the example

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; } } }

To create this example in Flash Professional

  1. Create a new ActionScript 3.0 Flash document and save it.
  2. Download the Flash Professional source file (asgreeter_flash_source.zip) from the top of this page.
  3. Unzip the file and make sure the Greeter.as file is in the same directory path structure as it is in the ZIP file, relative to your Flash document (the FLA file). When you import the class, it needs to have a directory structure that emulates the package path (com.example.quickstart).
    For example, if you named your Flash document "Greeter.fla", the folder containing the Greeter.fla file should have a com folder in it and your files should be relative to your working folder as:
    .../Greeter.fla
    .../com/example/quickstart/Greeter.as
  4. Using the Text tool, create a dynamic text field on the Stage. Give it the instance name output.
  5. With the keyframe on Frame 1 selected, open the Actions panel and enter the code below.
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();
  1. From the main menu, choose Control > Test Movie to see the result.

To create this example in Flash Builder

  1. Create a new Flex application.
  2. In Source view, add the following event handler attribute to the mx:Application tag: initialize="initApp();"
    The mx:Application tag should now look like this:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="initApp();"> </mx:Application>
  1. Add a Text component with an 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>
  1. Add the following 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>
  1. Click the Run button on the toolbar to see the result:

Result

This content requires Flash To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player. To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player.

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.


For more information

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:

  • "Object-oriented programming" in Programming ActionScript 3.0
  • Creating your first ActionScript class (video tutorial)

Related Flash Quick Starts

  • Embedding fonts
  • Loading images and Library assets in Flash with ActionScript 3
  • Loading and saving local files with the FileReference class
  • Event handling
  • Display list programming
  • Working with symbols and the Document class
  • Programming with arrays
  • Programming with the Vector class

More Like This

  • Programming with the Vector class
  • Creating, populating, and resizing the DataGrid component
  • Customizing and sorting the DataGrid component
  • Filtering and formatting data in the DataGrid component
  • Display list programming in ActionScript 3
  • Using ActionScript 3 drawing commands
  • Embedding fonts
  • Event handling in ActionScript 3
  • Getting started with Flash CS4 user interface components
  • Using the Label component

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement