Tutorial: Understanding Classes in AS3 Part 2

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 code in the first frame of your Flash movie like an IT chipmunk, to moving your code to its own Class.

I promised that in Part 2, we’d learn how to identify chunks of code that should be moved into their own Classes. But before we do that, it’s important to talk about what a Class is. And if you haven’t learned how to extend a MovieClip symbol in your library to write a Class around it, this tutorial is for you!

Take THAT, eggheads

Disclaimer Dear Eggheads: This tutorial is between me, a designer-turned-coder, and readers who want to learn more about Actionscript programming who likely are not Computer Science graduates. The terminology i use may not be 100% accurate, and some of the things i say may inflame your nerd rage and your unwavering demand for technical accuracy. But this article is not for you. Stop reading now. Go write some slash fiction about Captain Kirk totally doing it with the dog from Battlestar Galactica, and leave us alone to learn.

OOP: There It Is

A Class is an element of OOP – Object Oriented Programming. OOP is a flavour of coding where different objects – or things – interact with each other to solve a problem. If you’re a game programmer, the problem can be described as “How do i make a fun, functional zombie game?” The word “object” is synonymous with “Class”. You could say that Actionscript 3.0 is a Class Oriented Programming language, but the eggheads would stab you in the face.

She-Nerd

She-Nerd SMASH!!

So a Class is a thing – a chunk, a morsel, a module of code. By writing your Classes the “right” way, you’ll find you can re-use Classes from project to project. By writing them the “wrong” way, you’ll still probably wind up with a project that has nice, well-organized code that makes sense if you re-visit it a year later.

The three principles or rules to follow if you want to maximize the advantages of OOP are encapsulation, inheritance and polymorphism. We’ll be taking a brief, gentle look at inheritance in this tutorial, because i think it’s the easiest to understand when you’re starting out.

Inbred Twins

Herbert n’ Zed inherit their genes from their paw n’ their sis

Classes contain methods and properties. (Another word for “method” is “function” or “behaviour”. Another word for “property” is “field”.) A method is something a Class can do. A property is something a Class is.
Let’s explain this somewhat better by using a crappy example that a lot of OOP tutorials use. You have a Class called “Dog”. Methods of Dog – things that Dog can do – include:

  • bark
  • sniff
  • humpLeg

Properties of Dog – things that dog is – include:

  • color
  • breed
  • favouriteTreat

Another way to think of it is that methods are verbs, and properties are adjectives.

Ugly Dog

The OOP Dog example rears its ugly head

Let’s Get Real

The Dog example is almost entirely useless to us as programmers. In all my years of experience, i have never written a Dog Class. But i HAVE written my fair share of music and movie players in Flash. Let’s look at the methods and properties of a media player.

Methods of our MediaPlayer Class – things that a media player can do – include:

  • play
  • pause
  • stop
  • scrub
  • changeVolume
  • loadMedia

Properties of our MediaPlayer Class – things that a media player is, or things that describe its state – include:

  • isPaused
  • songDuration (or movieDuration)
  • isFullScreen
  • volume

Note that the method “changeVolume” probably changes the property “volume”.

Snowths

We’re gonna need a method called “turnVolumeWayWayUp”

You’re Already an Expert

The good news is that as a Flash developer, you’ve been using Classes this whole time, though you may not have known it. A MovieClip is a Class. It has methods and properties. Let’s look at some of the methods of a MovieClip – things a MovieClip can do:

  • gotoAndPlay
  • stop
  • hitTestPoint (determine whether a point is colliding with me)

And some properties of a MovieClip – things a MovieClip is (or things that describe its state):

  • x and y
  • alpha
  • rotation

Eggheads: Are you still reading this? i told you to take a hike. Don’t jump down my throat. i know that a few of these methods and properties actually belong to Classes that MovieClip inherits from, but we’re just learning, alright? Leave us alone. Go out and LARP or something.

LARP

No Pain, No Awesome

Just as you can make the leap from stowing all your code in the first frame of your movie to putting it in an .as Class file, you can (and should) make the leap from having all of your MovieClip instances “physically” present on your stage, to keeping them in the library and drawing them to the stage using code. There are many advantages to using a code-only approach which probably won’t become clear to you until you go through the excrutiating growing pains of “WHY THE HELL AM I DOING IT THIS WAY??” like i did.

Growing Pains

Growing Pains: excrutiating

So create a MovieClip in your library. NOTE: If you don’t know how to do this, you may already be in over your head. Go check out a beginner Flash tutorial and come on back.

In order for you to make the MovieClip available to you through code, you need to give it a linkage name. Here’s how:

  1. Open your Library (CTRL+L)
  2. Right-click the MovieClip symbol
  3. In Flash CS3, choose “Linkage”. In Flash CS4, choose “Propeties”.
  4. Check the box that says “Export for ActionScript”
  5. In the “Class:” field, type a logical name for your MovieClip. It’s best practice to start this name with a capital letter. Don’t use any spaces – capitalize each new word SoThatItLooksLikeThis. (This is called “Pascal case”)
  6. Click “OK”
  7. If you are a Mac user, and you’re saying “What’s a CTRL?? What’s a right mouse button?? i’m freaking OUT, man!”, go buy a PC ;)

Linkage CS3

Setting linkage for a library item in Flash CS3 …

Linkage CS4

… and in Flash CS4.

Linkage Name

Choosing a linkage name

Did you notice, before you hit OK, that there was a field labelled “Base Class:” that said “flash.display.MovieClip”? If this is your first time creating a library linkage, or if it’s old hat and you’ve never noticed this field, prepare to blow your own mind: you’ve just used the first principle of OOP – inheritance.

My Mind Done Blow’d Up

Here’s what’s going on behind the scenes. “MovieClip” is a built-in Class that the creators of Actionscript wrote. When you give your library item a linkage name, you are actually subclassing, or inheriting, from the MovieClip Class. That means that your new Class “Dog” or “MediaPlayer” or “EnemySpaceship” can now do all the stuff that a MovieClip can do. It can gotoAndPlay, it can stop, it can hitTestPoint, etc. It also inherits all of MovieClip’s properties – x and y, alpha, rotation, etc. – things that a MovieClip is, things that describe its state.

So now we’re getting to the point. When you create a library linkage like this, Flash is automagically creating a new Class (“Dog”, “MediaPlayer”, whatever). You don’t have to write it. But you CAN write it, if you want to. And since that’s what this tutorial is all about, then oh yes – we want to.

Oh Yes – Let’s

Start a new .as Class file. You can do it in the Flash IDE, you can write it with Notepad or Notepad ++ or any other text editor. i highly recommend Flash Develop. Remember our first Understanding Classes tutorial? Here’s the structure of a Class:

AS3 Class Structure

i chose these colours from Arsenio Hall’s wardrobe

So here’s what our empty Class code should look like:

package
{
	import flash.display.MovieClip; // Import statement(s)

	public class Dog extends MovieClip
	{
		// Class definition

		private var isBarking:Boolean; // Instance variable(s)

		public function Dog()
		{
			// Constructor function
			trace("i am a dog");
		}

		// Other functions
		private function bark():void
		{
			isBarking = true;
		}

		private function stopBarking():void
		{
			isBarking = false;
		}
	}

}

Let’s take note of a few important things.

  1. i’m calling my Class “Dog”. That’s because the linkage name in used in the Flash library was “Dog”. Note: not “dog” or “DogClip” or anything. D-o-g. Same capitalization, exact same name.
  2. And note that the linkage name can be completely different from the library symbol name. My library symbol could be called “This is a thing what i created in teh Flashs”. Doesn’t matter. Actionscript can’t “see” the library item name. It can only “see” the linkage name.
  3. Finally, remember that the Class file name has to be the same as the Class name. If our Class is called Dog, we save the file as Dog.as. Pull any other shenanigans, and you’ll get errors.

Silly dog

i SAID “no shenanigans”, DOG

i mentioned mysteriously in the last tutorial that the word “extends” is an inheritance word. When you create a linkage name in the library, Flash automagically writes a Class for you, and automagically extends (inherits from) MovieClip. Now that we’re writing the Class ourselves, nothing is automagic. We have to explicitly say that Dog (or whatever) extends (inherits from) the MovieClip Class. When this is all done correctly, Flash understands that there is a connection between the linked library Class “Dog”, and the “Dog.as” Class we just wrote.

You may or may not know the code for dynamically placing a linked library item on the stage. Here it is, using Dog as the example:

var dog:MovieClip = new Dog();  // or var dog:Dog = new Dog();
addChild(dog);

“BUT WAIT!”, you say. “I THOUGHT DOG HAD TO START WITH A CAPITAL LETTER??” Okay, first of all, stop yelling. Lower-case “dog” is the name of the variable that contains an instance (a stamp, a copy) of our master Dog Class. We could use “dog1″, “dog2″, or even “thisIsACopyOfDog”.

When you addChild(dog), you add your instance (stamp, copy) of the Dog Class to the list of things for Flash to draw to the stage (the viewable area that the player sees).

To confirm that your custom library Class is working, test your movie. You should see the trace action “i am a dog” in the Output window. (Press F2 to see the Output window – the trace action won’t appear on the stage)

What’s the Point?

You may be wondering why we went through all of this agony. The easy way is just to draw a dog and make it a MovieClip, and then leave it on the stage. There are many, many advantages to what we’ve just done. Let me list a few:

  • You can now add as many Dogs to the stage as you like dynamically. Until now, you had to add them by hand. If you needed another dog, you (the creator) had to drag one out of the library. Now you can create an “Add Dog” button. When the player presses it at run-time, your code dynamically places dogs on the stage. Now the code is doing the work, not you.
  • We’re edging closer to the next OOP principle, encapsulation. Within our Dog class, we can store methods (things that a Dog does) and properties (things that a Dog is). Every time we initialize (make a stamp or copy of) Dog, Dog can run a bunch of Dog-specific setup routines: initializeSenseOfSmell, testBarkTone, prepareToChewShoes. If you do it “right”, you’ve created a self-reliant, self-contained Class. Now every time you have a project that needs a Dog (or a MediaPlayer, an ImageGallery, a CountdownClock), you can just copy that .as Class file to a new project. If you’ve done everything “right”, it’ll just work.
  • The more you start abstracting your thinking, the more you’ll be able to write generic Classes that do a number of different jobs. You might not have another project that needs a Dog, but your generic Animal Class would still do the trick.
  • There’s a problem that Actionscript 3 introduced where you can’t always access certain pieces of MovieClips until they’re drawn to the screen. Writing a custom Class for your library elements can overcome this problem.

What’s Next?

Moving your frame code to an .as Class file was the first step. Learning how to write custom Classes for your linked library items is the next step, since it builds on (hopefully) familiar MovieClip territory and your existing knowledge. In the next tutorial, we’ll take a look at that big wad of code in your Main.as file and try to figure out which methods and properties can be logically grouped and moved into their own Classes.

For more tips, tricks and tutorials, check out our Flash and Actionscript 911 feature.

36 thoughts on “Tutorial: Understanding Classes in AS3 Part 2

  1. TJ

    “The word “object” is synonymous with “Class”.”

    I didn’t want to be an egg-head, but you’ve forced me to… =’(

    An object and a class are two very separate things, and IMHO the distinction between them is an important concept in order to avoid confusion in the future (how come Dog.bark() doesn’t work!?), especially if you start to throw in static methods/variables. An object is what contains the methods and variables, the class is what defines exactly what methods and variables an object has. Although I’ll admit it does get a little confusing when you realize that flash stores Classes AS Objects…

    Other than that, it was a good tutorial, and to offset my egg-headedness, I’ll say that I thought all your other inaccuracies were justified by the scope and target audience of the tutorial.

    Reply
    1. Ryan

      TJ – Ack! i’ve been Egg-Headed!

      Are you familiar with the educational kids’ show The Magic Schoolbus? They have tons of ridiculous, innaccurate stuff throughout the episode just to keep the story moving along, and they devote the last five minutes of the show to a scripted call-in segment where “viewers” phone them up to tell them what they got wrong.

      So this is all very much in the spirit of The Magic Schoolbus … but thank you for your clarification! It’s a good extra credit point to study.

      - Ryan

      Reply
  2. Josh

    Here’s one explanation of the difference between a class and an object that I always liked: A class is like a blueprint for a house. An object is one particular house made with that blueprint. You can use the same blueprint to make more than one house.

    Reply
  3. Carl Jackson

    I found this and the previous example to be very useful, I’ve been studying for days and I think I finally have external AS classes down for the most part.

    I do have a problem that I’m struggling with still. I’m using the Flex SDK with Flash Develop to make my code, and I simply can’t figure out how to get things in my classes to show up on the stage/canvas/whatever.

    I did wrap it in a UIComponent, but i can’t get it to show up. If i strip the AS3 code for making a circle off of the main.mxml page onto an external class, in this case being MakeCircle.as, I can’t get it to show up on the display no matter what i do.

    I don’t think you are a flex guy, but if you can help, I’d be happy to paste the code.

    Reply
    1. Ryan

      Thanks, Carl. You’re right – i’m not a Flex guy, but we do have a few readers who use Flex. You’ll likely get an answer here some time tomorrow.

      - Ryan

      Reply
  4. Kaolin Fire

    I use FlashDevelop, but I stay out of the mxml stuff. Do you have a main document class? (the “always compile”?)

    Would be happy to poke at your code — kaolin [a]^t erif{.org}

    Reply
  5. Helene Vallee

    Another great tutorial, Ryan. Even though I’m taking courses on AS3 from the code-only point-of-view, I find what you have to say very helpful in a practical sense. the egg-heads who write the books and courses on AS3 may know their stuff when it comes to code, but as designers, we’re already using classes and objects everyday and it’s good to fit the new knowledge into the framework of the practical stuff we already get.

    One tiny detail: functions are all public. A quirk of AS3 that is a result of them running out of time when they were writing it. (Straight from Colin Moock… he wrote the book, after all.) I wouldn’t mention it except it really helped me understand why I kept getting segments of the “magazine” where the page turns would suddenly malfunction. Understanding that every function is public helped me resolve this.

    Keep it coming, Ryan. You rock!

    Reply
    1. Ryan

      Thanks, Hélène! But i’m afraid i don’t understand your point about all functions being public. What about functions that you explicitly declare as private?

      private function iCannotBeInvokedFromOutsideThisClassBecauseIAmPrivate():void
      {
      }
      

      We’re going to get into private vs public in a future tutorial, but why not get a sneak peek? If you were to drop the piece of code above into a Class, and then you instantiated the class and tried to call the function, you’d get an error. The function is defined as private, and is inaccessible outside the Class.

      Am i misunderstanding you?

      Reply
  6. Bwakathaboom

    Soooo…if I wanted to have the dog object walk around the screen I make the dog class call upon an AI class which calls upon a pathfinding class which calls upon a movement class etc. etc. etc. until I have a source folder of 800 .as files all of which do exactly *one single thing* each?

    Waaahh! Adobe ruinzed my Flashs!!! If XML navigation weren’t sooo much better in AS3 I probably wouldn’t even bother.

    Reply
    1. Ryan

      Bwakathaboom – naw. No need to get that granular, although i share your frustration.

      There’s no rule saying that you have to be perfect at this from square one. Don’t listen to the eggheads – that’s what they’ll have you believing. Remember in math class when they made you go through a bunch of problems like 7+7+7+7 before they taught you multiplication, just to show you that there’s a better way? i find the best way to approach learning OOP is to charge in and make your mistakes. There’s plenty of time to hone your technique.

      And in an upcoming Understanding Classes post, i’ll show you one or two ways to cheat and speed things up. It’ll make the eggheads crap their pants. Good fun.

      - Ryan

      Reply
    1. Ryan

      Josh- Oh, i see! Thanks for the help. i didn’t understand, because we’ve LEFT THE TIMELINE IN THE DUST! Adios, [Spanish word for "timeline"]!!

      Now that we’re writing everything in separate .as Class files, we need to declare permissions for everything. i mentioned in Part 1 that we’d be declaring everything “public” until we understood what that was all about.

      And, incidentally, public/private is what Part 4 of the series is all about!

      - Ryan

      Reply
  7. Pingback: untoldentertainment.com » Tutorial – Understanding Classes in AS3 Part 4

  8. Pingback: untoldentertainment.com » Tutorial: Understanding Classes in AS3 Part 3

  9. philh

    I’ll try and not be too long winded. I’m primarily an editor, that’s video editor who came to flash to try and build his own website. I’m on a journey. I use video. As an editor I found flash as a design tool quite easy to get to grips with, it had a timeline, and objects I could put in there and do things with. Then I started to discover AS and slowly slowly began to trade in my timelines for script. It began to make sense, but only slowly. I began to understand the fundamentals of AS2. I can’t remember now but there were things I struggled with and thought might work better in AS3. So I took a look and quickly discovered that everything I’d learnt in AS2 would have to be relearnt. I gave up and then realised I shouldn’t. I’ve spent the last few weeks reading, trying to come to grips with class in AS3. I haven’t really written any AS3 script yet. I just want to try and get to grip with it conceptually in my brain before I make mistakes. There’s little things niggling me at the moment and I’m sure they’ll be many more. I just found your webpage and for someone like me it felt like coming home. Honestly it’s mincemeat out there. I won’t bore you with a million questions, just one thing I need to be clear about right now. I need to understand how that ‘document class’, the one you right in your main fla figures with all your other class.as’s. When you write class files is the idea to pull ‘copy and paste’ those into the ‘document class that you write for that particular fla or am I completely off somewhere else, thx.

    Reply
    1. Ryan

      philh – you’re getting me jazzed here. Thanks for your warm encouragement.

      When you compile (test/build your movie, hit CTRL+Enter – whatever you want to call it), and your swf runs, the interpreter is the part of the Flash Player that reads all of your AS1/AS2/AS3 code instructions and does what you tell it to do (hopefully).

      If you write your code on the first frame of the main timeline, the interpreter knows that’s one of the first places to look for code. It starts at the top of that code, and starts chewing through it.

      But if your code all exists in external .as Class files, how does the interpreter know where to start? It doesn’t! So we have to TELL it where to start.

      So in that little field labeled “Document Class” (which is a very unhelpful way they’ve decided to name it), picture instead that it says “START HERE”. You type in the name of the Class where you’d like the interpreter to START looking at your code.

      The Eggheads call this your program’s “point of entry”. Hang on to that term – if you branch out to other languages, you’ll see it crop up again from time to time.

      Does that help?

      Reply
  10. philh

    Hi, thx for your speedy response and sorry for rambling. Yes, that’s what I already understood, that ‘Document class’ was the point of entry. What confuses me is how other classes are called on once you have your point of entry class. I’ve now read your next two parts in this series and I think It’s becoming clearer. Am I write in thinking that as long as ‘other classes reside in the same folder as your ‘document’ or ‘main class that all you need do is call them by name alone from within your ‘document’ or ‘main’ class a bit like you would an ‘instance’ if writing your script in the first frame of he timeline?

    Thx once again and yes, take much encouragement. Your explanations are a breath of fresh air.

    Reply
  11. Misa

    I must say that I find these tutorials to be quite interesting and of high quality although I was a bit shocked when I saw one of the pictures you used. Its the picture of that creepy “demon” dog (“The OOP Dog example rears its ugly head”) which really scared the hell out of me. I don’t know why, perhaps because I love animals, but that picture simply made a huge impact on me because the dog is not ugly but scary :)

    Nevertheless I still find the tutorials in here very good and I tend to recommend it to my fellow colleagues which are trying to make a lift off in the world of AS3. Thanks again for the huge effort in making these tutorials.

    Reply
  12. Sbliss

    Ryan
    Please help me resolve the Error 1120: “Access of undefined property someMainApp.addChild(group)” message I am getting for the below code. it supposed to create 2 rectangular shapes on Sprite (as the DisplayObjectContainer).

    var rect1:Shape = new Shape();
    rect1.graphics.lineStyle(1);
    rect1.graphics.beginFill(0x0000ff, 1);
    rect1.graphics.drawRect(0, 0, 75, 50);

    var rect2:Shape = new Shape();
    rect2.graphics.lineStyle(1);
    rect2.graphics.beginFill(0x0000ff, 1);
    rect2.graphics.drawRect(0, 0, 75, 50);

    rect2.x = 50;
    rect2.y = 75;

    var group:Sprite = new Sprite();
    group.addChild(rect1);
    group.addChild(rect2);

    someMainApp.addChild(group);

    Thanx in advance for your assistance.

    sbliss

    Reply
    1. Ryan

      Sblis – i can’t help with your problem by looking at the code out of context like this. Do you just have this code copy/pasted to frame 1? If so, the error is valid. Flash has no idea what “someMainApp” is, and neither do i. It’s never mentioned in your code until that very last line.

      If you’ve got the code on frame 1 of the timeline, change the last line to:

      addChild(group);

      Reply
  13. Sbliss

    Ryan

    The code is an example in Colin Moock’s “Essential ActionScript 3.0″ that i am using to learn AS3. The instruction says it should run. Because I am new to AS3, I don’t what and how to define to get the code run.

    Reply
  14. Pingback: BJPcommunication.com» Archives » Tutorial sur les classes AS3 et la POO

  15. Alejandro

    Hey Ryan-

    I know its been forever since this article was written, but as this is one of the few ‘fresh start’ tutorials for AS3 out there, I feel that expressing my problem here would be met with the most ‘user-friendly’ answer.

    As I attempted to link the “Dog.as” to the Flash project by typing it into the “Document Class: ___” area, an error message appeared saying, “You must specify a unique class name that is not associated with any library symbols.” This error message also appears when I have already loaded the Dog.as file and attempt to name the Linkage of a Movie Clip to “Class: Dog”. I have looked around the Internet for a solution, and found advice saying to rename the “Class” names to unique names, but to keep the “Base Class” names the same. I have found this information a bit useless considering how knowledgeable of Flash I am. I appreciate any help you can give me on this subject and also thank you for getting me started on my way to understanding and using AS3 like a real egghead.

    Reply
    1. Ryan Henson Creighton

      Hey, Alejandro. Thanks for your encouragement. i’m always up for answering a polite question.

      Go back to Part 1 of the series and set up your file so that your document class is called Main. Just as the Dog.as class is paired with the Dog MovieClip in your library, the Main.as class is paired with your main swf movie (remember that your Flash main timeline is just one big MovieClip).

      When you write those two lines of code to instantiate an instance of the Dog class and add it to the display list, those lines of code go in your Main class’s constructor function (or wherever). So Main, the main movieclip (your main timeline) creates an instance of Dog called “dog” (the Dog Movieclip gets paired up with the Dog .as file and they become one). Then Main places that instance in its display list, so that it gets drawn to the screen.

      Yeah?

      Reply
  16. Luthimir

    “If you are a Mac user, and you’re saying “What’s a CTRL?? What’s a right mouse button?? i’m freaking OUT, man!”, go buy a PC ;) ”

    Or get a two-button mouse – “ctrl” in OSX == “Command” for most Windows functions, there is a control button on the new keyboards too :)

    Reply
    1. Ryan Henson Creighton

      Unfortunately, MacHeads will have to wait until the next WWDC, when Steve Jobs is expected to announce that 2-button mice are cool, and that it’s okay to have one.

      Reply
  17. Brandon

    Ryan,

    As someone that works in training for a very tough field (Nuclear Power). I found your article to be extremely refreshing and useful for this topic. I have been doing a lot of flash development recently and started only a month ago not knowing what a tween was. To now making much more complex Javascript calls and using xml to dynamically run different scenarious (pictures, text videos, sound) at points in time. I really need to separate my stuff into classes and have been looking for answers. You have done a phenomenal job at delivering. BTW, to all you eggheads, the correctness of the information IS important although how you get there IS not. So Ryan KUDOS and ty.

    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>