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.

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.

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.

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!

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:
1 2 3 4 5 6 7 8 9 10 11 | 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.

Same directory. We can get fancy later.
The Care and Feeding of Classes
Classes demand a particular structure:

Notice a few things:
- Package (whatever that is) wraps the whole thing
- the Import statements (whatever they are) come next
- the Class Definition (huh?) wraps everything else
- 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

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:
1 2 3 4 | 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

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:
1 | 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:
1 | var myclip:MovieClip = new MovieClip(); |
you have to include an Import Statement like this at the top of the file:
1 | 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

This is where you actually start writing your Class. Here’s the format:
1 2 3 4 | 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:
- You must use standard naming conventions. Don’t start the name with a number, and stay away from spaces and special characters.
- Use a capital letter to begin your Class name
- 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

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:
1 2 3 4 | function myFirstFunction():void { var myVariable:String = "someValue"; } |
we’ll get an error if we try doing this:
1 2 3 4 | 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:
1 | 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

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:
1 2 3 4 | public function Main() { } |
As with Classes, you have to follow a few rules with your Constructor Function:
- The Highlander rule: “there can be only one”. i believe other languages allow you to have multiple Constructor Functions, but AS3 does not.
- The name of the Constructor function must be the same as the name of the Class.
- Make sure it’s public.
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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).

This is what it looks like in Flash CS3

… 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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; } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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.
Popularity: 28% [?]











(13 votes, average: 4.69 out of 5)
Email This Post
That image of the class structure is one of the most useful things I have seen. I’m very interested in finding out what you recommend in terms of peeling code off the main class.
I also had a bit of a chuckle about “uniquely naming your package”
Hey, thanks Merve! In Part 2, i’m going to show actual examples of where i’ve decided to Classify bits of code, and why i did it. Too many OOP tutorials give you hypotheticals, like Moock’s zoo game analogy in Essential Actionscript 3.0. Examples like those were never enough for me to figure things out in the real world of coding. So hopefully Part 2 will be a gritty, inner-city look with no suburban sugar-coating. ( … wtf?)
Yes!!! That’s my reference book and it has to have the least helpful set of examples I’ve ever read (I mean, who wouldn’t want their first AS3 project to be about zoos and virtualpets)
nice work. should help beginners and intermediates quite nicely. Moock’s examples worked well for hypothetical examples of various design patterns later in the book. However you are both probably correct that it would have been nice to see a “real world” example of the necessity of each design pattern.
especially nice work on the visuals.
Thanks, Sketch. Not to knock Moock too terribly – his Essential Actionscript 2.0 book was very very good – but i think that these days, he just knows too much to be an effective teacher. He quickly bogs down his writing with minutiae and accurate but nit-picky terms and definitions. To teach well, i think you need to remember what it was like to know nothing.
good stuff, should def help someone new to AS3 wrap their head around opp’ing and such.
Event as a relatively seasoned AS3′er – I found your Class Package color coded graphic very explanatory. Will def refer to it next time I’m trying to explain package structure – thanks!
samBrown – oh good! Thanks so much for your feedback.
I second that those class structure diagrams are a very nice way of showing the structure. This is the structure I use, but you know seeing it like this I’m struck with one thing that doesn’t make the best organizational sense. Why have the constructor after the instance properties? I suppose because the constructor is often used to initialize the instance property values, so therefore reading top to bottom you run into the property definitions first, and then the initialization code. However, wouldn’t it make more sense to have the constructor immediately after the class definition? The class definition and constructor both share the same name, so it would make updating the class name quicker (find and replace aside, there would be no scrolling past the properties). Also since the constructor is a “special” method in the class, it would make sense to separate it from the rest of the methods. If it was above the properties, these would act as a separator.
Consider a structure that utilizes getter/setter methods. Not only do these methods act as if they are properties to the outside world, but they often utilize a private property, so it arguably would make sense to group them with their associated property, or at least immediately after all the properties. In both cases the constructor gets pushed below another method, which doesn’t help with readability.
And there you go, your daily dose of organizational nitpickery satisfied :)
Anselm – your points are well-taken. In fact, just a few weeks ago, i saw some code where the programmer puts the instance variables at the bottom of the Class, which blew my mind.
As with anything like this, the thing that makes the most sense is NOT doing the thing that makes the most sense – it’s doing what everyone else is doing. If this is the way that most people code, then for better or worse, it’s how you should code. Makes for less of a shock when you jump into someone else’s Class file. (Where are all the instance variables???)
Love the tutorial, really great info. I right now like to have all my code in the 1st frame of my timeline as i don’t really need to update my programs (namely because they’re not worth updating), and most of my code is divided into functions so I don’t too hard a time managing it, however, from now on I’ll try to upgrade myself to at least a “pro” status, but hey, if you’re making one .as file, why not make 20?
Hope to see more tutorials like this! :)
Brennon – thanks for your encouragement!
i had to check myself after posting this article, because i thought “well, the next step is to teach people to split their code out into 20 Classes”, but then i thought “wait – hasn’t this come full circle? Isn’t that the same problem we had with spaghetti code?”
But no, it’s not quite the same thing (thank goodness). Believe it or not, splitting your code into 20 Classes can make you code faster, because you can finish writing a Class and forget about it, and it’s not taking up room in one huge long scrolling Main.as Class. Saved time on the scrolling alone is worth it. And the organization that a (free) program like FlashDevelop affords is crucial.
Shouldn’t ‘Class’ be lowercase?
public Class Main extends MovieClip –> public class Main extends MovieClip
Good catch, Christian – thanks! Shows how much i rely on code correction and highlighting in Flash Develop. i will fix.
Oh, and I like this post. It illustrates the idea easily without making it so conceptual.
“public Class” in your script generates error messages.
It needs to read “public class” with a small “c”.
Robert – thanks. Christian discovered this problem earlier today, and i thought i had fixed it. Is there a straggling “public Class” that i missed?
Beautiful post! I rate it 5 out of 5! I’m now itching to read how to have the main class interact with a secondary class like loadXML() or RadiansToDegrees().
Thanks, Mark! The two pieces of code you mention are actually methods (AKA functions), not classes, but i’ll try to remember to explain the difference between those two things in Part 2.
- Ryan
[...] Classes in AS3 Part 2 by Ryan, September 9, 2009 // In our first thrilling look at Understanding Classes in Actionscript 3.0, we talked about how Classes are structured, and how you can make that leap from stashing all your [...]
[...] and to move all of that first-frame code into its own seprate .as Class file. That’s where Understanding Classes began. It seemed like a pointless step – whether the code was in its own frame or in its own Class [...]
[...] Understanding Classes Part 1, you freed yourself from the timeline. In Part 2, you took a little detour and learned how to [...]
I cannot tell you how relieved I was to have stumbled across your site. As a designer/illustrator, I had decided to go back to school this year to jump into AS3, it seemed like the natural thing to do. Up until 10 minutes ago I was sure that I probably wouldn’t continue. As a visual person blocks of code simply did not make sense to me. Because you have broken it down visually, I think there might be a chance for me. Thank you, thank you, thank you so much!
Tanya – thanks so much for your warm words of encouragement! I’ll be teaching an intro to Flash/Actionscript course at college in January, and you’ve done a lot to reassure me that i’ll be able to communicate this stuff to a group of artists.
- Ryan
Good luck, and stay calm. If it helps our teacher adds a little role playing into the course… visual exercises using paper airplanes to help with the connection to right side of the brain. Strange… maybe, but as a visual person it seems to work.
-Tanya
Ryan
Does the Flash Develop utility run on the Mac environment.
sbliss
Sbliss – i’m not a Mac guy, but i think i read somewhere that it does not. A quick Google search will turn up forum threads where people are discussing alternatives, if memory serves.
This post could not be more helpful! I watched lynda.com tutorials, I read so many other sites. This is a great simple explanation for newbies to learn about Classes. Explaining every step and every piece of code is SO vital to understanding. Thanks so much!
Thanks for your encouragement, Mary!
God bless you, Ryan! Your tutorial is perfect for an AS2 coder like me, who’s striving to make the leap to AS3. I tried countless times to figure out classes in AS2 but I always failed. Today I started to see the big picture. Thank you so very much!!!
Man … the comments on this post are downright heart-warming. If there’s anything anyone else would like me to explain about Flash, let me know! i’m happy to tackle new topics.
Directly Quoting what mary said “This post could not be more helpful! I watched lynda.com tutorials, I read so many other sites. This is a great simple explanation for newbies to learn about Classes. Explaining every step and every piece of code is SO vital to understanding. Thanks so much!”
your blog is really very helpful. i got hooked with the pimp my game series. now its Soooo much more.
Great work man.
\m/
“God bless you, Ryan! Your tutorial is perfect for an AS2 coder like me, who’s striving to make the leap to AS3. ”
Exactly! I read a AS2 “dummies” book and I’ve been piecing my Java knowledge to help understand AS3, and your stuff really, really helps! I’ll keep reading!
Also, just curious, what IDE (I think that’s what they’re called) do you use for AS3? Like Flash Develop and Adobe Flex? Thanks!
Thanks, Vincent. i’m a BIG FAN of FlashDevelop, though i must admit my experience is limited. i’ve never used Flash Builder or Eclipse. But i HAVE used Visual Studio C# Express Edition, and FlashDevelop is a lot closer to that experience.
i’m not a power-user by any means, but just being able to type an open { bracket, and FD automagically puts in the close } bracket for me must be saving me YEARS of typing, when you add it all up.
Another tip: i use CTRL+D a lot. It duplicates a line. i discovered it by accident when trying mistyping CTRL+S to save. If i want to change a line, but i want to comment it in case i screw things up, it’s very quick to CTRL+D to copy the line, then comment one of them and change the other.
There’s also CTRL+I, which is global find and replace. It’ll search through ALL of your .as files, recursively through all the sub-folders if you let it. VERY handy.
Ryan, I loved the simplicity of your teaching and am reading Mook’s mammoth now. I’ve read peachpit and even Adobe’s beginner, but I am so confused about one thing about classes. In FlashDevelop, once you create the “Main” class, you can put code in the point of entry and it works, ok. When I create another package and code it, they don’t seem to understand each other. I can’t get the sprite in one .as file to appear and my addChild in the constructor is leading nowhere. I’ve played with it for over an hour and have read the first few chapters of Mook’s book twice! I feel like an idiot (maybe I am). Any comment?
Thanks, Dave.
i think you can probably solve your problem with an import statement.
You’re probably already using one for movieclip in your Main class:
import flash.display.MovieClip;
So if you have a sprite called MySprite in another package, and you want to refer to if from Main (or wherever) in another class, AND MySprite is part of the com.assets.stuffIMade package, use an import statement in Main:
import com.assets.stuffIMade.MySprite;
In FlashDevelop, MySprite should light up after a few seconds, and you should get code hinting for your MySprite class. All feexed!
Please let me know if that solves your problem.
- Ryan
[...] http://www.untoldentertainment.com/blog/2009/08/25/tutorial-understanding-classes-in-as3-part-1/ [...]
it feels nice referring people to your visually pleasing and easy to understand tutorial :)
[...] Ryan explains in this tutorial, Flash beginners tend to put Actionscript code everywhere. On different frames of the timeline, [...]
Great tutorial, thank you.