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 / ActionScript Technology Center /

Object-oriented programming with ActionScript 3.0

by Peter Elst

Peter Elst
  • peterelst.com

Content

  • What are classes?
  • Basic OOP concepts: Inheritance vs. composition
  • Encapsulation
  • Polymorphism

Created

2 July 2007

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScript Flash Builder Flash Professional OOP

Requirements

User level

Beginning

Required products

  • Flash Professional (Download trial)

Sample files

  • oop_as3.zip (30 KB)

In object-oriented programming, developers often use the term "architecting an application." This analogy is not far off the mark. You can approach any project as if you are its architect, and use object-oriented principles as building blocks to structure your code. As you develop your application, you can think of your code modules as the blueprints that form the foundation of your applications. Just as you can use one blueprint repeatedly to build similar structures, you can repurpose your code as needed to achieve your desired functionality.

The concept of classes is at the heart of all object-oriented code development. If you're not already familiar with object-oriented programming (OOP), this article will get you started writing ActionScript 3.0 classes. Writing classes has never been easier than with ActionScript 3.0. Whether you are new to ActionScript altogether or are new to working with ActionScript 3.0, you'll find that writing classes allows you to create projects that are easier to manage and maintain.

The concepts covered in this article will help you begin writing more portable, reusable code and move beyond the world of procedural code and timeline functions in Flash.

What are classes?

Classes are nothing more than a collection of functions (called methods in this context) that provide a blueprint for any number of instances that are created from it. By changing some variables (or in OOP terminology, properties) of a class instance, or by passing different values as arguments to its methods, the same underlying class can have widely different outcomes.

Another way of understanding a class is to compare the tasks performed in the Flash authoring environment. While ActionScript classes are created programmatically, they are basically analogous to the concept of importing assets and then working with symbols in the Library panel and the symbol copies (instances) on the Stage. The symbol instances on the Stage are similar to class instances. The different instances on the Stage—despite coming from the same symbol—can each individually have different properties settings that affect how they appear (such as color, alpha transparency, rotation, and so on).

The ability to generate multiple instances (that can appear and behave differently) from the same object is one of the reasons why classes are so powerful. An ActionScript class is even more powerful than a symbol in the Library because, as a developer, you have complete control over how an object looks and behaves. There are many properties and methods accessible using ActionScript 3.0 that you cannot access through the Flash authoring interface. Additionally, ActionScript classes make it possible to dynamically animate objects during runtime that are outside the scope of timeline-based animations. Finally, writing your own ActionScript classes promotes reusability because the functionality you create can be repurposed.

Let's see how this looks in code:

Brick.as

package com.adobe.ooas3 { public class Brick { public var color:String = "red"; public function Brick() { trace("new "+ color +" brick created"); } } }

The Brick.as code above illustrates one of the most basic implementations of an ActionScript 3.0 class. The class holds just a single method and property. As you walk through each line of code, the following facts come to light:

  • First, a package is defined. Packages allow you to structure your code in folders on your hard drive and prevent class name conflicts. In this example, the class is saved as Brick.as (the exact case-sensitive class name), inside a folder named "ooas3", which in turn is stored in an "adobe" folder that itself is contained within a folder called "com".

    By convention, package names are usually the domain name of the project in reverse order, followed by the project name. Doing this ensures that the package name is unique and there is no risk of any other project's classes conflicting with your own.

  • Then the class is defined and set as public (more about access modifiers later). In our example the class is named "Brick".
  • The next line of code declares a public property "color" of a type String that we will be using in the class. The value of color is set to red. There are better ways of working with class properties—as you'll learn about when I discuss encapsulation.
  • Finally, the Brick method is defined. Note that this is not just any method. Every class has a constructor, which is a method that is automatically called when a new instance of the class is created.

    You can easily recognize constructor methods because they always use the same name as the class within which it is defined. Knowing this, you can easily see that, for the Brick class, this Brick method is its constructor.

    Inside the method we are tracing out a message to the Output panel that reads: "new red brick created". The trace statement incorporates the value of the variable color, which we defined with a default value of "red."

To quickly test this class, launch Flash CS3 Professional, create a new blank ActionScript 3.0 FLA, and write the following lines of code on the first keyframe on the main Timeline:

import com.adobe.ooas3.Brick; var firstBrick:Brick = new Brick();

If you run Test Movie (select Control > Test Movie), you'll see that the Output panel now displays "new red brick created" (see Figure 1).

Output panel of Brick class getting instantiated
Figure 1. Output panel of Brick class getting instantiated

The traced message in the Output panel means that your ActionScript 3.0 class is functioning correctly. Now it is time to start doing some more advanced things with classes.

Basic OOP concepts: Inheritance vs. composition

There are just a handful of concepts at the core of OOP. This article covers the most important ones: inheritance, encapsulation, and polymorphism. I also discuss a few related topics to help you put these ideas into context.

Without a doubt, inheritance is the most well-known principle of OOP. Inheritance can be defined as the ability to inherit properties and methods and extend the functionality of an existing class in a new one.

If you're thinking ahead, you might imagine creating a new "Wall" class that extends the "Brick" class you created earlier. However, that is not how inheritance works.

Looking at the relationship between a brick and a wall, the best way to code this is not through inheritance but rather by a concept called composition.

A simple rule of thumb determines whether the relationship between classes is one that warrants inheritance or composition. If you can say class A "is a" class B, you're dealing with inheritance. If you can say class A "has a" class B, the relationship is one of composition.

Here are some examples of inheritance:

  • Cat "is an" animal
  • Engineer "is an" employee
  • Rugby "is a" sport

Here are examples of composition:

  • Wall "has a" brick
  • Computer "has a" keyboard
  • School "has a" teacher

So what is the difference in how inheritance and composition are implemented? Let's compare how this works, starting with inheritance:

Animal.as

package com.adobe.ooas3 { public class Animal { public var furry:Boolean; public var domestic:Boolean; public function Animal() { trace("new animal created"); } } }

The Animal.as code is the base Animal class, which you will now extend using inheritance with a Cat class:

Cat.as

package com.adobe.ooas3 { public class Cat extends Animal { public var family:String; public function Cat() { furry = true; domestic = true; family = "feline"; } } }

If you look at the Cat class, the constructor assigns values to three different properties. On close inspection, only one of these properties (family) is defined in the Cat class. The other properties (furry and domestic) come from the Animal base class.

While this not exactly the most practical example, you can see how class inheritance allows you to build upon existing functionality to create a new blueprint for you to start using as you develop your project.

Now if you wanted to create half a dozen cats, you could simply do this by instantiating the Cat class, which has all the properties already set up, rather than using the generic Animal class and having to define the properties again and again for each instance.

New in ActionScript 3.0 is an override keyword that is used when (you guessed it) you want to override a method defined in the class that you extended. This useful feature prevents you from accidentally running into naming conflicts with methods between classes that extend each other.

On the other hand, composition doesn't have any formal syntax like the extends keyword. Composition simply instantiates its own instance of any class it wants to use.

Let's take the Brick class created earlier. In this next example you'll create a Wall class that uses composition to instantiate instances of the Brick class:

Wall.as

package com.adobe.ooas3 { import com.adobe.ooas3.Brick; public class Wall { public var wallWidth:uint; public var wallHeight:uint; public function Wall(w:uint, h:uint) { wallWidth = w; wallHeight = h; build(); } public function build():void { for(var i:uint=0; i<wallHeight; i++) { for(var j:uint=0; j<wallWidth; j++) { var brick:Brick = new Brick(); } } } } }

In the code above, the Wall class accepts two arguments passed to its constructor, defining the width and height in bricks of the wall you want to create.

Let's do a quick test of this class by instantiating it on the main Timeline of a blank FLA file:

import com.adobe.ooas3.Wall; var myWall:Wall = new Wall(4,4);

If you run Test Movie (Control > Test Movie), you'll see that 16 Brick instances are created with corresponding trace statements displayed in the Output panel to create a 4 x 4 wall (see Figure 2).

Output panel of Wall class getting executed
Figure 2. Output panel of Wall class getting executed

Apart from the difference in class relationship between inheritance and composition (as I discussed earlier), composition has the advantage of being able to add functionality to another class at runtime. It allows you to have control over the creation and destruction of class instances, whereas with inheritance the relationship between the classes is fixed and defined at the time the code is compiled.

Encapsulation

Now let's move on to another important principle of OOP called encapsulation. The underlying concept of encapsulation deals with what methods and properties your class exposes to the outside world.

Up until this point you've always set methods and properties as public, but is that really what you'd want to do?

If you want your code to be stable, and if you want to develop projects that are least prone to bug and errors, you'll want to restrict the ways in which other classes can interact with your code.

The key here is to only have those methods and properties available that are required as settings for the class, and restrict access to the rest. Using this approach, you'll have a limited number of places in your code to debug when something goes wrong in the interaction with your class.

ActionScript 3.0 includes the following keywords as access modifiers to methods and properties:

  • public: allows access from anywhere
  • private: can only be accessed within its own class
  • protected: can only be accessed within own class and subclasses
  • internal: can be accessed by all classes in same package

Let's put this concept into practice. Take a look at the following example:

Person.as

package com.adobe.ooas3 { public class Person { private var _age:Number; public function get age():Number { return _age; } public function set age(val:Number):Boolean { if(_age < 0) return false; _age = val; return true; } } }

The code example above shows a Person class with a private property _age of a Number type. Even though you want to allow the age of the person to be set, you still opted not to use a public property here. Instead you are routing the age value through the use of a getter/setter method.

Getter/setter methods (as implemented in the previous example) appear as if they are properties, but they behave like methods.

When you set the age property, it calls the age setter method that assigns the value to the private _age property after validating it. In this case, you know that a person's age can't be a negative value. If the given value is valid, the setter method returns true, or else returns false.

The major advantage of this approach is that every time the age property is set, validation occurs because the age value is always routed through the setter function. If the age property were set as public, every method in your class that wants to use the age property would first need to check if its current value is valid.

Polymorphism

The final concept I cover in this article is polymorphism. The concept behind polymorphism is based on the idea of different classes implementing the same method names.

Even though this is a very simple concept, polymorphism has some interesting implications. The first major advantage is that it allows classes to be interchangeable at runtime. There are no hard-coded references to specific method names for specific classes.

For example, imagine you have a Teacher class and a Student class. You could implement a teach method for the teacher and a study method for the student, but polymorphism allows you to write the code so that the two classes both implement a work method. Although a Teacher and Student class will clearly have a different implementation of a work method (one teaches, the other studies), you can use a shared generic method name, creating a single interface through which they can be accessed:

Teacher.as

package com.adobe.ooas3 { public class Teacher { public function work():void { trace("I am teaching"); } } } Student.as package com.adobe.ooas3 { public class Student { public function work():void { trace("I am studying"); } } }

Any class that gets passed an instance of either the Teacher or Student class does not need to do any type checking to determine whether it is dealing with a teacher or a student instance (or any other class implementing the same methods for that matter) but it can directly call the work method.

You can enforce polymorphism between classes through the use of something called interfaces. These are similar to classes in that they define a set of methods, but interfaces are different than classes because they do not have an implementation. Interfaces simply define a "contract" of the methods a class needs to implement in order to be valid.

Here's an example of an interface called IWork:

IWork.as

package com.adobe.ooas3 { public interface IWork { function work():void; } }

As you can see from the code above, an interface looks suspiciously like any other class. But there are a few differences. Most developers choose to name an interface name so that it begins with a capital I (a common naming convention for interfaces, although it is optional). Also, instead of a class keyword, interfaces use the interface keyword. Additionally, as you analyze the code, you'll see that in the section where you would expect to see some code for the work method, only its method signature is defined.

The interface above requires that any class that implements it must have a method called work that has a return type of void.

Let's see how the Teacher and Student class implement this interface:

Teacher.as

package com.adobe.ooas3 { public class Teacher implements IWork { public function work():void { trace("I am teaching"); } } }

Student.as

package com.adobe.ooas3 { public class Student implements IWork { public function work():void { trace("I am studying"); } } }

That was easy. By simply adding the implements keyword, you now have set up both the Teacher and Student classes so that they are required to implement the work method. If you try removing or renaming the work method from either of the two classes, you'll receive a compile-time error message.

By having classes all implement a common interface, the interface can actually be used as a data type. Let's look at the following example:

Supervisor.as

package com.adobe.ooas3 { public class Supervisor { public function Supervisor(worker:IWork) { worker.work(); } } }

In the example above, you have a Supervisor class that can be passed an instance of a class implementing the IWork interface. In this way, the interface is being used as a data type.

The ActionScript compiler knows that any class instance implementing this IWork interface will have the work method defined. Therefore, it doesn't complain about a possibly undefined method when the code is compiled.

You can quickly test the Supervisor class by pasting the following code on the first Frame in the main Timeline of a blank FLA in Flash CS3 Professional:

import com.adobe.ooas3.*; var supervisor1:Supervisor = new Supervisor(new Teacher()); var supervisor2:Supervisor = new Supervisor(new Student());

If you run Test Movie (Control > Test Movie), you'll see two lines appear in the Output panel. The first line displays "I'm teaching" and the second displays "I'm studying" (see Figure 3). These trace statements are, of course, exactly what you'd expect by passing a new teacher and student instance to the Supervisor constructor.

Figure 3. Output panel of the Supervisor class using polymorphism
Figure 3. Output panel of the Supervisor class using polymorphism

Type casting

That brings up the next question: What happens when you try to access class-specific methods or properties of Teacher or Student (other than the work method) that weren't defined in the interface?

The Supervisor class uses the IWork data type for any instance that is passed to its constructor – so if you were to call any other method, the compiler has no way of knowing whether that is implemented. The compiler will report an error.

You can work around this is by using something called type casting by converting the instance from this generic IWork data type back to the Teacher or Student instance.

The way this is accomplished is by using the is and as keywords, as follows:

package com.adobe.ooas3 { public class Supervisor { public function Supervisor(inst:IWork) { if(inst is Teacher) { var teacher:Teacher = inst as Teacher; trace(teacher.tenure); } if(inst is Student) { var student:Student = inst as Student; trace(student.averageGrade); } } } }

In the code above, the is keyword checks whether the worker instance passed to the constructor is of the specific type Teacher or of the type Student.

If it is a teacher instance using the as keyword, you are able to type cast the instance to that specific class, so you can access its specific methods and properties. In this case you could, for example, have a Boolean tenure property set in the Teacher class.

The same holds true if we're dealing with a student instance. If the is keyword confirms that you are working with a student, you can type cast the generic IWork instance to a student instance and access the averageGrade property.

This is a very useful behavior. You can see how using polymorphism in this way benefits your projects when you have a collection of classes that need to accept any number of data types, as long as they implement a common interface. When you need to get into the specific method implementations of the class implementing the interface, type casting makes this possible.

Where to go from here

This article walked through the basics of object-oriented programming in ActionScript 3.0. From the concept of classes, the building blocks of your application, through inheritance, encapsulation, and polymorphism.

You learned how classes can extend each other through subclassing or by using composition. Additionally, you now know how to restrict access to your class by using access modifiers and providing an API with getter/setter methods. Finally, you've seen how you can enforce multiple classes to implement the same set of methods through the use of interfaces and how to convert generic instances back to a specific implementation by using type casting.

That's quite a feat. If you've followed along, you are now ready to start putting these new concepts into practice and reap the benefits of object-oriented programming in your ActionScript 3.0 projects.

Be sure to check out the ActionScript Technology Center for more in-depth articles and tutorials, and to gain more knowledge of working with ActionScript 3.0.

If you haven't already, take a look at the Flash Quick Starts to get more specific information about classes and programming tips on developing Flash applications in ActionScript 3.0.

More Like This

  • Colin Moock ActionScript 3 videos
  • ActionScript 3 Design Patterns excerpt: Factory method and MVC
  • Top five benefits of ActionScript
  • Tips for learning ActionScript 3.0
  • Introduction to event handling in ActionScript 3.0
  • Adobe Flash Platform ActionScript reference for RIA development
  • ActionScript 3 Cookbook excerpts: From custom classes to the rendering model
  • Creating a preloader in Flash
  • ActionScript 3.0 overview
  • ActionScript 3.0 from the ground up

Tutorials & Samples

Tutorials

  • Flash iOS Apps Cookbook excerpt: ActionScript optimization
  • Introduction to Robotlegs – Part 3
  • Introduction to Robotlegs – Part 2
  • Introduction to Robotlegs – Part 1

Samples

  • ActionScript 3 samples for Flash Professional CS5

ActionScript Blog

More
06/09/2012 New Flash Tools: Flash Optimizer 2.3
06/09/2012 Flash Optimizer 2.3
05/27/2012 How to add an image to android gallery (CameraRoll) using adobe air
04/22/2012 ActionScript 3.0 BitmapData, Clone, and ColorTransform

ActionScript Cookbook

More
03/20/2012 PDF Portfolio Navigational TOC
02/29/2012 Embed Stage3D content inside Flex application components
02/13/2012 Randomize an array
02/09/2012 Using Camera with a MediaContainer instead of VideoDisplay

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