Now that we know how to create classes in AS3, we can now learn to implement these custom classes written by us into objects in the flash movie.Before continuing, it is highly recommended you go through the article, Getting Started with ActionScript 3.0 to learn how to create your own classes.The custom class :: To start off, we will need an actionscript class. You could use the sample greeter class provided below or you could use any other class you have at hand.Copy the code below, open Flash and create a new ActionScript 3.0 class and paste the code and save the file as "greeter.as" Sample greeter Class ::
package {
public class greeter
{
private var my_name:String;
public function greeter()
{
}
public function init_name(n:String)
{ my_name=n;
trace("Initialized Name!")
}
public function hello()
{ trace("Welcome "+my_name+".");
}
}
}
Creating Objects from our class ::Now that we are done writing the actionscript class, we can start with Flash.Open Flash and create a new file (Ctrl+N) and select ActionScript 3.0 from the list. This should open a blank Flash movie with a white stage.Now before we start working, save the movie (Ctrl+S) and choose a file name of your choice and make sure you save it along with the actionscript file in the same directory.Now select the first keyframe, right click and select Actions from the context menu... This should open the actions window, a miniature version of the one which you would have seen while writing your class.This is where the code goes...
Code ::
var n1:greeter=new greeter();
n1.init_name("Anand");
n1.hello();
var n2:greeter=new greeter();
n2.init_name("Dimitri");
n2.hello();
Code Description ::
var n1:greeter=new greeter();
This line of code creates a new object with an instance name "n1", in this case an object of class greeter.
As soon as an instance of the object is created, the constructor function is called and instances of variables and functions are created, specific to each instance.
n1.init_name("Anand");
Here, we are calling the "init_name" function from the n1 instance of the greeter object with arguments "Anand".
n1.hello();
This calls the hello function of the n1 instance of greeter object.
Similarly, in the next few lines, a new instance of the object greeter, "n2" is created and functions are called from this instance.
Now that we are done with the code, we can test the movie. To do so, press Ctrl+Enter and you can see the output generated by the trace function in the output window...
In case of any existing confusion about objects and classes, this schematic should help you better understand them...
Incase you face any problems or if you have any sujjestions, feel free to leave a comment.