-------------------------------------------------------------
READ MORE:
https://www.youtube.com/watch?v=eeuDe3x7iD0
http://www.untoldentertainment.com/blog/2009/08/25/tutorial-understanding-classes-in-as3-part-1/
------------------------------------------------------------------------------
Tutorial: Understanding Classes in AS3 Part 1
87 Replies
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:
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:
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:
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
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:
- 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:
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
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:
- 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:
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 tellFlash 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:
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
IMPORT CLASSES
------------------------------------------------------------------------------------------------------------------
import com.example;
On class file:
package com.example
{
public class Test
{
public function display():void
{
trace("here");
}
}
}
---------------------------------------------------------------------------------------------------------------http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00001795.html
---------------------------------------------------------------------------------------------------------------
Import the component classes
Each component is associated with an ActionScript class file that defines its methods and properties. In this section of the tutorial, you will add ActionScript code to import the classes associated with the application's components. For some of these components, you have already added instances to the Stage. For others, you will add ActionScript later in the tutorial to create instances dynamically.
The import statement creates a reference to the class name and makes it easier to write ActionScript for the component. The import statement enables you to refer to the class by its class name rather than its complete name, which includes the package name. For example, after you create a reference to the ComboBox class file with an import statement, you can refer to instances of the combo box with the syntax instanceName:ComboBox, rather thaninstanceName:mx.controls.ComboBox.
A package is a directory that contains class files and resides in a designated classpath directory. You can use a wild card character to create references to all the classes in a package: for example, the syntax mx.controls.* creates references to all classes in the controls package. (When you create a reference to a package with a wild card, the unused classes are dropped from the application when it is compiled, so they don't add any extra size.)
For the application in this tutorial, you need the following packages and individual classes:
UI Components Controls package This package contains classes for the user interface control components, including ComboBox, DataGrid, Loader, TextInput, Label, NumericStepper, Button, and CheckBox.
UI Components Containers package This package contains classes for the user interface container components, including Accordion, ScrollPane, and Window. As with the controls package, you can create a reference to this package by using a wild card.
DataGridColumn class This class lets you add columns to the DataGrid instance and control their appearance.
WebService class This class populates the ComboBox instance with a list of problems or offenses. For this class, you will also need to import the WebServiceClasses item from the Classes common library. This item contains compiled clip (SWC) files that you will need in order to compile and generate the SWF file for your application.
Cart class A custom class provided with this tutorial, the Cart class defines the functioning of the shopping cart that you will create later. (To examine the code in the Cart class file, open the cart.as file located in the component_application folder with the application FLA and SWF files).
To import these classes, you will create an Actions layer and add the ActionScript code to the first frame of the main timeline. All the code that you will add to the application in the remaining steps of the tutorial should be placed in the Actions layer.
- To import the WebServiceClasses item from the Classes library, select Window > Common Libraries > Classes.
- Drag the WebServiceClasses item from the Classes library into the library for the application.Importing an item from the Classes library is similar to adding a component to the library: it adds the SWC files for the class to the library. The SWC files need to be in the library in order for you to use the class in an application.
- In the Timeline, select the Form layer and click the Add New Layer button. Name the new layer Actions.
- With the Actions layer selected, select Frame 1 and press F9 to open the Actions panel.
- In the Actions panel, enter the following code to create a stop() function that prevents the application from looping during playback:
stop();
- With Frame 1 in the Actions layer still selected, add the following code in the Actions panel to import the classes:
// Import necessary classes. import mx.services.WebService; import mx.controls.*; import mx.containers.*; import mx.controls.gridclasses.DataGridColumn; // Import the custom Cart class. import Cart;