Tutorial: the basics of object-oriented programming in ActionScript 1, 2 & 3

[ Download the presentation slides ]

A long time ago, I put together a crash course on object-oriented programming in ActionScript. I'm still receiving positive feedback about it now, so I decided to put it online.

It's a learn-by-example tutorial about OOP in Flash. The primary goal I had in mind when making this tutorial was to teach the basics of OOP to Flash designers in a couple of hours. Well, I explained the theory in a few hours and I gave everybody ActionScript files with a focused example of every part that I explained. And some say this worked :-) .

For optimal understanding of this very condensed tutorial, it's best that you know how to use Flash and that you know what ActionScript in Flash is good for. You need Adobe Flash CS3 to open and compile the .fla files.

Very schematically, the course outline:

  • The "object"
  • Welcome to the class
  • Inheritance and polymorphism
  • Composition
  • Class Interface
  • Exception handling
  • Event handling and dispatching

Wherever possible, I made the same example for every version of ActionScript (from 1 to 3). So, you can easily compare the different versions and check out how old school cool the AS1 prototype looks. I've added inline instructions and explanations by means of comments in the code.

The "object"

What is an object? Everything can be described in an object via data abstraction: with properties and methods. Think of a bike, for instance. A bike is a vehicle. Every conventional bike has basic structural properties like a frame, 2 wheels, a saddle, 2 pedals, a chain, steering, etc. The main function of the bike is to ride. Via the bike's bell you can make a ringing sound. Instance properties of the bike are its size, its color, ... Whether a bike is red or blue changes nothing about the structure of the bike, the color is only a changeable property. Structurally identical bicycles can exist in many different colors. The red and the blue bike are 2 instances of a bike that was built by the same mold or blueprint.

For the fun of it, just try to make this kind of data abstraction for other objects (both physical and non-physical) by identifying the objects' properties and functions that seem relevant (ex. try to describe a Cat).

The definition of the structure of an object is what is called a class. An object is a specific instance of a class. In object-oriented programming, a system or program is constructed by means of objects.

Welcome to the class

Programming involves syntax. One of the first things I think you should know to start programming OO, is how to write a class (or prototype). A class is often described as a blueprint. Download 01_Class.zip and see how to write a class / prototype in ActionScript 1, 2 & 3. Take a good look at the constructor, i.e. the place where we can say that an instance of a class is being constructed. Every class has a constructor. If you happen not to write one, then an empty constructor is added automatically.

In the first sample, you'll find a class "Person" having properties like name, gender and birthdate and with a  function to calculate the age in years based on the given birthdate. Open the Flash file and check out the framescript to see how you can use that Person class. Run the example (CTRL/Command - Enter) and look at the output trace to see what happened.

Geeks (like myself) should also check out the similarities between ActionScript 1 and JavaScript. They're alike because both languages are ECMAScript dialects.

Inheritance and polymorphism

Inheritance is the mechanism where a class inherits the properties and the methods of a hierarchically higher class. By inheriting properties and methods from another class you create a hierarchical classification. Inheritance also makes it possible to create variations of base classes.

In this context, think for example about the hierarchy of vehicle > bike, or: mamals > apes > humans. Download 02_Inheritance.zip and check out the example where we extend the MovieClip (read inherit all properties and methods from the MovieClip class) and create a specific kind of MovieClip that automatically bounces around on the stage.

In the AS2 & AS3 version, you can configure the link between the MovieClip and the class by opening the library (F11), point to the MovieClip, right-click and choose "Linkage...". In AS1, you need to register a "class" to be associated with a MovieClip by code with Object.registerClass.
Please note that in this example we're using package names. Packages are mainly used to separate classes in order to avoid name collisions (i.e. to avoid confusion with identical class names). In our AS1 example, we simulated package names by creating the "namespace" within a global Object.

By convention, to create a package name, we take the domain name but written backwards (in our example be.novio) and then the name of the project (in our case "be.novio.samples") and then an arbitrary category (which makes be.novio.samples.inheritance for instance). Also by convention, class names are written in CamelCase and in package names we write every word lowercase.

An ActionScript class file always needs to be put in a folder structure exactly as the package name describes. For example, the be.novio.samples.inheritance.BounceAround class needs to be put in a folder be/novio/samples/inheritance. The name of the file in which the class resides has to be identical to the class name, with .as extension.

Directly related to inheritance are the benefits of polymorphism: the ability of objects belonging to different classes to respond to operations of the same name, each one according to the right class-specific behaviour. Say what? Oh well, check out the example in the same zip.

Inheritance can improve reusability of code and makes it possible to centralize logic. However, badly constructed class hierarchies (which happens very often when the goal of a system isn't defined clearly on beforehand) can lead to unmanageable systems. Manageability can be improved by applying composition, because composition enables switching between different implementations.

Composition

Some say to always favor composition over inheritance. If you just need services from another class, use composition. If your class behaves very much like an existing class: consider inheritance (but choose composition ;-) ). If you need the advantages of polymorphism: use inheritance. In ActionScript you can only inherit from one class at a time, so that's an extra reason to favor composition over inheritance. Download 03_Composition.zip and see the alternative for the previous example where we extended the MovieClip. The class BounceAroundComposition "HAS-A" MovieClip that's bouncing around on the stage, whereas the class BounceAround from our previous sample "IS-A" MovieClip.

Class Interface

An interface is often described as a "contract" for a class implementing it. Basically, it's a definition of the methods that minimally need to be implemented. Using interfaces can lead to more flexible code when using interfaces "as-if" they're the datatype: this way, you can switch between implementations with minimal effort. The class interface was first introduced in ActionScript 2. Download 04_Interface.zip to see a dummy sample.

Exception handling

Errors abort code execution and that's a good thing because errors must always be exposed (also read this post about dealing with runtime errors).
Code in which something can possibly go wrong should be wrapped in a try-catch block. Please note that the finally-block always executes. Errors bubble up the stack, up to the stage (where the plugin catches them).
Don't hesitate to throw your own errors in your code when execution is better to be aborted because of certain conditions in your program. It's very often a good idea to subclass the Error with specific types of Errors, such as IllegalArgumentError, OutOfBoundsError, or WhateverError. The more information, the easier it becomes to track and correct bugs. Download 05_Exceptions.zip to look at the silly example I created.

Event handling and event dispatching

Events determine flow. Events orginate from user actions such as key presses, mouse gestures or messages sent out by objects, the system, etc. An instantiated event first get processed by an event dispatcher and then the event is being associated with event handlers of interested objects. Event-driven programming is a good way to accomplish loose coupling between different encapsulated parts or components.

Download 06_EventHandling.zip to check out the sample about handling component events (good ol' v1, bad ass v2 & smooth v3 components). And also download 07_EventDispatching.zip to find out how you can dispatch custom events (and handle them off). Subclassing the Event is elegant, always consider it.

It's good to have notion of the event flow of an event object like for example the mouse click event that moves through the display list. A mouse click first goes from the stage down to the target component (capture phase) and then the click event starts bubbling back up to the stage (bubble phase). Read more about it here.

Please note that in AS3, there's somethin' tricky with the declaration of objects on the stage. You have two options. In this example, we switched off the automatic declaration of stage instances (Publish settings > Flash tab > ActionScript 3 Settings > deselect Automatically declare stage instances) and stage instances are automatically "mapped" with the class' properties with the same name. In the other case, stage instances are created automatically as a property. If a property with the same name already exists in your class, then you've got issues. You can access the automatically created instances in your class with the getChildByName method instead.

So what's next?

If you're serious about becoming a good programmer (in any language), I would advise you to learn about object-oriented design (OOD). There are great books explaining how to structure your code in order to solve common problems. Many of these books are inspired by the book Design Patterns: Elements of Reusable Object-Oriented Software (written by the Gang of Four). Probably the biggest challenge in programming is learning to write code that's reusable, encapsulated, maintainable, flexible and scalable. Becoming a good programmer is a continuous growing process that's being fed by project experience, expert advice and study.

There are at least 2 widely accepted development frameworks that I think you should check out when you're serious about developing "rich internet applications": Cairngorm (for Flex) and PureMVC (for both Flash and Flex).

Any kind of feedback/tips to help me improve this blog post is welcome, so don't hesitate to drop me a line via e-email: hans{ at }novio.be.

Thanks to my colleague Vincent Vanderheeren for reviewing this blog post and giving me useful tips.

This entry was posted in tutorial and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

5 Comments

  1. J. Heikkinen
    Posted November 14, 2008 at 11:31 am | Permalink

    Hello,

    the links for composition and 04interface.zips seem not to work. This is a great post by the way, haven’t managed to find anything of the similar subject as of yet, and I’d greatly appreciate if you’d fix those links to point to the correct location. Thank you, and keep up the good work.

    - JH

  2. Posted November 15, 2008 at 1:11 am | Permalink

    The links to 03_Composition.zip and 04_Interface.zip are fixed now. Sorry about this and thanks for letting me know.

  3. Posted January 30, 2009 at 11:04 am | Permalink

    Hello Hans,
    Well done from writing this blog! I have am issue with a existing Flash project that is written in AS1 and 2. I would like to eventually have it all in valid AS3 code and the transfer from 2 to 3 should not be so hard. What I’d like to know is whether I could change all the code that utilizes .prototype to create ‘classes’ with methods and registers the class as an object (and also sometimes uses ‘loose’ imperative code with a symbol) to decent OOP-code.
    And also, I’d like to get most of the code within symbols out of the .fla files and into seperate .as files, any hints and tips on that?
    Regards, Jurgen

  4. Posted June 2, 2009 at 8:42 pm | Permalink

    Thanks a lot for the nice tutorial. Great examples. They compile great in CS4.

  5. Luke B
    Posted December 14, 2009 at 6:18 pm | Permalink

    First time I’ve ever commented on a blog, but was so impressed by your useful examples I had to leave a reply………thanks!

2 Trackbacks

  1. By 123-tutoriels.com on November 10, 2008 at 9:43 am

    Tutorial: the basics of object-oriented programming in ActionScript 1, 2 & 3 | by Hans Van de Velde…

    A learn-by-example tutorial about OOP in Flash….

  2. [...] The basics of OOP in ActionScript 1, 2 & 3 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*