Object-oriented programming (OOP) is generally the best way to code in most languages. It helps by grouping together similar code and by having the ability to reuse the code. This tutorial will be based in Flash CS3, using ActionScript 3.
First off, AS3 requires that you use the package { } code structure and the class { } code structure within it. An example would be this:
package <package_name> { class <class_name> { } }
You may only have one class per package structure. If your application will use more than one class with the same package name, create another file for that class. When you want to include other classes, such as Flash frameworks, your own classes, or predefined classes and functions from Adobe, it is possible by doing this within the package, outside of the class, using the import keyword like the following:
package <package_name> { import flash.display.Sprite; class <class_name> { } }
If you know what functions are, then you are in luck. Classes are composed of a group of functions, called methods when within the class. To use a class, you need to instantiate, or create a new instance of, it. Instantiation has a general format:
var my_var:<class_name> = new <class_name>();
Like in “normal” (pragmatic) flash programming, var is required to create a new variable. The text after the ‘:’ is called the variable’s data type. If the data type of a variable is a string, then the variable would be created by doing:
var my_var:String = 'text';
The ‘new’ text is necessary, for it creates a new instance of the class, or else it might as well be a method or function you are calling. An example to instantiate would be like so:
var today:Date = new Date()
Methods are just like functions in which you have the same function structure, like so:
function <func_name> (<parameter>:<data_type>):<return_type> { }
Additionally, methods and variables can have other keywords prefixed to them such as public, protected, and private, called access modifiers.
public means that anyone (users, extenders, and itself) can use it.
protected means only extenders and itself can use it.
private means only the class itself can use it.
Well, you may have been confused by when I said “extenders” above. If you have a class that you like and want to add other methods to it without duplicating the class, you can extend the class with your own:
class mySprite extends Sprite { }
In the end you may find yourself with a file like this:
package my_classes { import flash.display.Sprite; import flash.text.TextField; class my_first_class extends Sprite; { public var my_str:String = "My First Class"; protected var something:Int = 4; public function my_first_class() { var tf:TextField = new TextField(); tf.text = my_str; addChild(tf); } } }
I hope you liked this post and that it helps you some way in the future.