Tutorial: Understanding Classes in AS3 Part 1

A reader named Ryan (no relation) recently requested that we create a post to help him and other beginners understand Classes. So this is an ultra-gentle primer on Classes – what they are, when to use them, and how to write them. If you’re stuck in an Actionscript 2 rut, or you’re new to Actionscript 3 and it’s blowing your mind, this should help ease you in a bit better.

The path i travelled from complete code newbie to the shock-inducing AS3 god that i am today ( er … hardly) went like this:

Beginner – i put my Actionscript code everywhere – on different frames of the timeline, embedded in nested MovieClips – if i can write code on it, i do.

Spaghetti Code

That’s called “spaghetti code”, and it makes your life as a programmer difficult.

Intermediate – Scattering code through my Flash movie makes my project an enormous pain to manage and update. i’m going to put ALL of my code on the very first frame of my movie, so i only have to look in one place for it.

First Frame

Placing all your code in Frame 1 was a good idea with AS2, but you can do better

Pro – i don’t understand Classes, but i have to take the plunge somehow. i’m going to move all of my first-frame code into a separate .as Class file. i hope that’ll be the first step to breaking everything up into Classes.

Code Goes Here

This is what we’re striving for

Shock-Inducing AS3 God – Man almighty – packing an entire project’s code into one .as Class file makes it an enormous pain to manage and update. i’m going to identify little modules of code and split them off into their own .as Class files. Hey … now i’m starting to use Classes like a superstar!

God

Not *THE* God – just *A* god

The Road to Pro

In this tutorial, we’ll help you move from Intermediate to Pro by moving your first-frame code to its own Class in a separate .as file. In Part 2, we’ll take you from Pro to God by discussing ways in which you can split that enormous file up into smaller Classes, and how to figure out which pieces would make good Classes.

Many of the AS3 tutorials you see on the Internatz are written so that you can just paste the code into the first frame and compile the project. This is because it’s easier on the tutorial writers – they assume that you know how to re-write that code to put it in its own Class. But what if you don’t know?

Let’s take a piece of frame code, and bring it outside our Flash .fla file into a separate .as Class file. Here’s the frame code we’ll be using:

var speed:int = 5;
var ball:MovieClip = new Ball();
addChild(ball);

addEventListener(Event.ENTER_FRAME, moveBall);

function moveBall(e:Event):void
{
  ball.x += speed;
  ball.y += speed;
}

This code grabs a MovieClip called “Ball” from the library and places it on the stage. On every frame, the ball moves to the right 5 pixels and down 5 pixels. We’re going to pretend that this code exists on Frame 1 of our Flash movie. (Note: you don’t need to copy/paste this code and try it, but go ahead. If you’re not sure how to create a ball MovieClip and link it in the library, you might be in over your head already. Read up a bit on super-basic Flash stuff, and we’ll see you again shortly.)

Now let’s create an empty, external .as Class file to hold all this code. So your project will consist of two files: the Flash .fla file, which has a Ball Movieclip in the library, and a Class file with an .as extension. This isn’t anything fancy – an .as file is just a plaintext (.txt) file that you save with a .as extension. So yes, you can even write this file using Notepad or your favourite text editor.

The .fla and the .as file should exist side-by-side in the same directory.

Side by side

Same directory. We can get fancy later.

The Care and Feeding of Classes

Classes demand a particular structure:

AS3 Class Structure Diagram

Notice a few things:

  1. Package (whatever that is) wraps the whole thing
  2. the Import statements (whatever they are) come next
  3. the Class Definition (huh?) wraps everything else
  4. the Instance Variables, Constructor Function and other methods/functions are tucked inside the Class wrapper. You can put these three things in any order, but this is how you’ll usually see them in the wild.

Package

AS3 Class Structure Package Diagram

Let’s deal with that Package thing first. The Package declaration is a way of grouping all your Classes together. Let’s say you’re working on a project with Bob. You have a class called “Stuff”, and Bob has a class called “Stuff”. By uniquely naming your Package, your classes won’t conflict.

But are you working with Bob right now? Are you on a big project with multiple programmers? No. So don’t worry about it. Forget Bob – just start with a generic Package declaration, which looks like this:

package
{
     // All the other stuff goes in here, between those curly brackets
}

(note that “package” has a lower-case “p” … i’ve used an upper-case “P” in the article just to make the word pop out at you)

Import Statements

AS3 Class Structure Import Statements Diagram

Different parts of the ActionScript 3 language are already split up into packages. When you put your code on a frame in Flash, all of those packages are automatically accessible. You don’t have to do any extra work.

But when you work outside Flash, you have to tell the compiler to go grab portions of the AS3 language before you can use them. So if you say this in an .as Class file:

var myclip:MovieClip = new MovieClip();

the compiler will throw you an error, effectively saying “What’s a MovieClip??”

Use an Import Statement to explicitely tell the compiler that you are using a certain part of the AS3 language. This is a giant pain in the ass, and a real roadblock when you’re starting out. As a beginner, you don’t know the package names you’ll need. This is just a painstaking trial-and-error period of looking in the documentation, or referring to other people’s code, and eventually you’ll memorize this stuff. (Or you can use a program like Flash Develop, which automagically figures some of it out for you.)

So if you use a line like this later on in your code:

var myclip:MovieClip = new MovieClip();

you have to include an Import Statement like this at the top of the file:

import flash.display.MovieClip;

(note: small “i” on “import”)

It’s like you’re saying “OK, compiler – we’re going to talk about fish today. Go get that fish book out of the library so that we’re all on the same page.”

Class Definition

AS3 Class Structure Class Definition Diagram

This is where you actually start writing your Class. Here’s the format:

public class Main extends MovieClip
{
    // The Instance Variables, the Constructor Function and Methods go here
}

Let’s break down that line piece by piece:

public Class Main extends MovieClip

We don’t really need to bother with understanding public vs. private vs. protected vs. internal. Those keywords are all in the same family, but here’s what you need to know: you gotta use “public” here. Don’t worry about the other possibilities until you’ve got a handle on the basics. If you don’t use “public” in the Class that replaces your first-frame code, you’ll get an error.

public Class Main extends MovieClip

We’re writing a Class! i’m getting all tiingly.

public class Main extends MovieClip

This is the name of the Class. Feel free to use your creativity here – you can call it whatever you like. But there are a few important rules:

  1. You must use standard naming conventions. Don’t start the name with a number, and stay away from spaces and special characters.
  2. Use a capital letter to begin your Class name
  3. When you save the file, the file MUST have the same name as your Class. If your Class is called Main, save the file as Main.as. If it’s called MyProject, save the file as MyProject.as. If you don’t do this, there will be trouble.

public class Main extends MovieClip

In earlier attempts to understand Classes and Object Oriented Programming (OOP), you may have heard of the concept of “inheritance.” That’s what the “extends” keyword is all about. Without exploring too deeply, we need to extend / subclass / inherit from an ActionScript 3 Class called MovieClip. Why? Because if we don’t, we’ll get yelled at. So just do it. Strive to understand it later.

public class Main extends MovieClip

That’s the Class we’re inheriting from. It’s like saying “my Class called Main can do everything a MovieClip can do, and more.”

Instance Variables

AS3 Class Structure Instance Variables Diagram

Instance Variables, sometimes called Fields, are variables that you need to access throughout your Class. If you’re familiar with the idea of scope, you’ll know that when we do this:

function myFirstFunction():void
{
   var myVariable:String = "someValue";
}

we’ll get an error if we try doing this:

function mySecondFunction():void
{
   trace(myVariable);
}

That’s because myVariable is scoped to myFirstFunction. It doesn’t exist outside that function.

If you want variables to be accessible to all the different functions in your Class, you declare them in the orange area on the diagram. You’ll also need to decide whether you’re making these variables public, private, internal, protected, etc. This is not a decision you need to make when all your code is on the first frame. OOP purists would absolutely FREAK OUT if they were reading this, but i’m going to recommend you make all your variables public for now. It’s the least error-prone approach when you’re learning, and when you know more, you can get a little fancier.

So here’s what a typical Instance Variable would look like at this point in the .as Class file:

public var myVariable:String;

Notice that we’re not even setting a value yet. We can, but we don’t have to. We’re just reserving a spot in the computer’s memory for this variable so that the whole Class can use it.

The Constructor Function

AS3 Class Structure Constructor Function Diagram

This Main Class will be what’s called the “point of entry” into our Flash program. It’s the first place where code will start being activated. A Constructor Function is like the point of entry in any Class. It’s the first function that’s fired when a Class is encountered by the interpreter.

Here’s what our Constructor Function should look like:

public function Main()
{
   
}

As with Classes, you have to follow a few rules with your Constructor Function:

  1. The Highlander rule: “there can be only one”. i believe other languages allow you to have multiple Constructor Functions, but AS3 does not.
  2. The name of the Constructor function must be the same as the name of the Class.
  3. Make sure it’s public.
  4. Don’t return a value – not even “void”. Constructor Functions are not allowed to return a value.

Putting It All Together

Let’s slap it all together and see what we’ve got:

package
{
    import flash.display.MovieClip;
    public class Main extends MovieClip
    {
        // instance variables go here

        public function Main()
        {
             trace("It works!");
        }  

        // other functions can go here
    }
}

Super! We’ve got the shell of a Class that we can use as our point of entry. (Make sure it’s saved as “Main.as”, or whatever you called your Class.) We’re just missing one step. We have to tell Flash that instead of looking to the first frame of the movie as our point of entry, we want it to look at the “Main” Class.

Open up the Properties panel in Flash and look for an empty field labelled “Document class:” (CS3) or “Class:” (CS4).

Document Class Flash CS3

This is what it looks like in Flash CS3

Document Class Flash CS4

… and in CS4

Note: you won’t be able to use this feature unless you’re targeting Flash Player 9 or above, with ActionScript 3 or above.

Type “Main” (without the quotes) into this field. Then save and compile. You should see the trace statement “It works!” in the Ouput panel.

All the Rest

Now that we have Flash looking to an external .as file to get the party started, let’s port over some of that first-frame code into our class. i’ll paste the clean version first, and then an identical copy with extensive comments so that you can follow along at home:

package
{
    import flash.display.MovieClip;
    import flash.events.Event;
 
    public class Main extends MovieClip
    {
        public var ball:MovieClip;

        public function Main()
        {
             ball = new Ball();
             addChild(ball);
             ball.speed = 5;

             addEventListener(Event.ENTER_FRAME, moveBall);
        }

        public function moveBall(e:Event):void
        {
                ball.x += ball.speed;
                ball.y += ball.speed;
        }
    }
}
package
{
    // This is the commented version.
    import flash.display.MovieClip; // since both Ball and Main are MovieClips,
              // we have to import the MovieClip Class 
    import flash.events.Event; // Later on, we use the Event Class, so
             // we need to import it here.
 
    public class Main extends MovieClip
    {
        // See how the Class definition and import statements
        // are inside the package curly brackets?

        public var ball:MovieClip; // We declare "ball" up here
             // so that the whole Class can refer to it

        public function Main()
        {
             // This is the constructor function!

             ball = new Ball(); // Since we already declared "ball"
               // as an instance variable, we can just refer to it
               // directly without redefining it
             addChild(ball); // Where does ball get added?  Main
               // is representing our Flash movie's main timeline,
               // so that's where the ball appears
             ball.speed = 5;

             addEventListener(Event.ENTER_FRAME, moveBall);
             // note: no need for the word "this", in case you
             // were wondering
        }

        public function moveBall(e:Event):void
        {
                ball.x += ball.speed;
                ball.y += ball.speed;
                // Again, because "ball" was defined up top, 
                // the moveBall method can refer to it
        }
    }
}

Are You Smart Yet?

Hopefully, you know enough now to port your whole wad of first-frame code to a separate .as Class file. That’s a baby step towards actually using the power of Classes to save yourself time in the future, and to keep your code organized, updatable, and a pleasure to re-visit.

In the next part of this tutorial, we’ll look at ways you can pick through your Wall of Code and identify which pieces you can could out into their own Class files.

For more Flash AS3 Tutorials and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.

87 thoughts on “Tutorial: Understanding Classes in AS3 Part 1

  1. Dave

    Ryan,

    many, many thanks for a clear, concise, succinct tutorial that makes plain and simple (AT LAST) a foundational aspect of AS3 for us newbs. For me it removes all confusion, doubt, uncertainty and ambiguities, leaving only a clear understanding and strong comprehension of the salient points presented.

    regards and best wishes.

    Reply
  2. alex

    many thanks as well for your effort and talent in writing the clearest and most enjoyable as3 tutorial I’ve ever read so far. regards

    Reply
  3. Ceylia

    Merci beaucoup Ryan pour tes exemples qui m’aident √©norm√©ment !
    J’ai beaucoup de mal pour ajouter les objets dans les classses, alors…

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>