Introduction to ActionScript 3.0/Class structure

From Wikibooks, open books for an open world
Jump to: navigation, search
Introduction to ActionScript 3.0
Introduction Class structure Variables and Data Type


Key concepts:


  • Objects, methods and properties
  • Classes
  • Packages
  • Importing
  • Variables and constants
  • Integrated development environments
  • Compilation
  • Document class
  • Object instantiation

Definition: Organization of classes in a society

Ah, classes. ActionScript projects are essentially made up of classes. (OK, there are interfaces too, but we'll cover them later.)

What is object-oriented programming?[edit]

Object-oriented programming, as the name suggests, is a programming paradigm that involves the creation of and interaction among objects. An object consists of two parts:

  • Properties that define the object's characteristics. For example, an apple may have properties like 'size', 'colour', 'juiciness', and so on.
  • Methods that define what the object can do. Methods are a subset of functions, which we'll discuss later. An apple may have methods like 'transport', 'eat', etc.

What are classes made of?[edit]

A class in ActionScript 3.0 looks like this. Let's look at it the elements of it, one by one.

package {
	import flash.display.Sprite;
	import flash.events.Event;
 
	/**
	 * @author WikibooksOverlord
	 */	
 
	public class Main extends Sprite{
 
		private const HELLO_WORLD:String = "Hello, world!";
		private var _username:String = "Daniel";
 
		public function Main():void{
			if (stage) init(null);
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
 
		private function init(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			//You can start changing from this line.
			trace(HELLO_WORLD); //This line outputs 'Hello, world!' for now.
			trace("Your name is " + name + ".");
			//Don't touch anything below this line.
		}
 
	}
 
}

Package definitions[edit]

package {

A package is a group of classes and other stuff inside a certain directory. The line of code above is called a package definition. For example, a package called 'fruit' might contain classes like Fruit and Apple.

The word 'package' here is a keyword. A keyword is a word used by the language for basic operations.

In our case, our class is stored in the main package, so we don't need additional information after the 'package' keyword. To specify that our class resides in the 'food' package, we can append the package name after the 'package' keyword:

package food{

If there's a 'fruit' package inside the 'food' package, we separate the larger package and the smaller package with a dot ('.'):

package food.fruit{

Apart from improving organisation, classes inside a package may have the same name as classes inside other packages. The package name is what distinguishes between them. You can have a class called applicances.Iron and another called materials.Iron.

Notice that the opening brace after the definition is matched by a closing brace at the end of the class file. Everything else in the program is set to be enclosed in this block. A block is a logical 'unit' of commands, or directives, enclosed by a pair of braces. By convention, everything inside a block should be indented, as shown above. Indentation improves code readability a lot, but it is not necessary for the program to work. (In fact, you could put everything in a class into one line and it would still work; however, the code will no longer be readable.)

Also notice that all package names start with lowercase letters, while all class names start with uppercase letters. This is a universally accepted convention that should be followed, even though the code still works if you rebel.

Import statements[edit]

	import flash.display.Sprite;
	import flash.events.Event;

An import statement is needed if we want to use classes from other packages, such as the standard library. In this case, we have imported two packages from the standard library: flash.display.Sprite and flash.events.Event. The standard library is a bunch of code that controls the basic operations of our Flash operation, such as text, graphics, sounds and so on. There are alternatives to the standard library, but that will not be covered here.

Sometimes, if we're lazy, we can import everything in a package with an asterisk (*):

	import flash.events.*;

As you can see, the syntax for an import statement is the 'import' keyword, followed by the path to the package. Note that although flash.display.Sprite and flash.events.Event are predefined classes, they are not keywords as they belong to the standard library rather than the language itself.

Once imported, we can use those classes in any way we want.

Class definitions[edit]

Class Structure: An organization of class with in a society.

	public class Main extends Sprite{

In this statement, the 'public' keyword tells us that we can use the class anywhere, even if we're outside the current package. This is known as a namespace attribute. Namespaces handle access control; that is, how the class can be accessed (surprisingly enough). There are only two possible namespace attributes for classes:

  • public tells us that we can use the class anywhere.
  • internal tells us that we can use the class in classes of the same package. It is the default attribute, so if you skip the namespace attribute altogether, the namespace will be automatically set to 'internal'.

After the namespace attribute, we find another keyword, 'class'. Then we see the class identifier Main. (An identifier is a 'name' that uniquely identifies something within a namespace. The full name of that something is the namespace plus the identifier. This will be covered later; for now, you can just treat the word 'identifier' as a special 'name'.)

After that, we see the keyword 'extends', followed by the class name 'Sprite'. This indicates that our Main class is a subclass of the Sprite class. Later, when we learn what the Main class actually is and what subclasses are, you'll understand what we're doing in this line. For now, just take it for granted.

Class members[edit]

Class members include properties and methods. Properties can be constants, which never change, or variables, which change.

	private const HELLO_WORLD:String = "Hello, world!";
	private var _username:String = "Daniel";

'private' is another namespace attribute we use on class members. There are four possible namespace attributes (apart from user-defined ones):

  • public tells us that we can use the member anywhere.
  • internal tells us that we can access the member in classes of the same package. It is the default attribute, so if you skip the namespace attribute altogether, the namespace will be automatically set to 'internal'. Later, we'll learn to access members of other classes.
  • protected tells us that only the class itself and its subclasses can access the member.
  • private is the most restrictive attribute. Only the class itself can access the member. Not even subclasses have permission.

In general, the attributes we choose should be as restrictive as possible.

In the lines of code above, we have defined and initialised a constant and a variable. In the next chapter, we'll cover what these two lines actually do.

Here are our method definitions:

		public function Main():void{
			if (stage) init(null);
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
 
		private function init(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			//You can start changing from this line.
			trace(HELLO_WORLD); //This line outputs 'Hello, world!' for now.
			trace("Your name is " + name + ".");
			//Don't touch anything below this line.
		}

In the above, we can see two method definitions: Main and init. Main is called the constructor of the class. When a class is initialised, this method is called to set things up. Note that constructors are always public. init is a private function that can only be called within the class.

There are a plenty of things in this code snippet that you don't understand. Don't worry - we'll cover everything in the first section. For now, just take it for granted that it works!

Comments[edit]

A comment does not change how the program work, but is an efficient way to add information to the program, whether for yourself or other programmers. There are two kinds of comments:

The first type of comments starts with // and is added to the end of the line. It cannot extend over one line. This type of comment is usually used to explain code.

			trace(HELLO_WORLD); //This line outputs 'Hello, world!' for now.
			trace("Your name is " + name + ".");
			//Don't touch anything below this line.

The second type of comments, enclosed by /* and */, allows for multiple lines. /* marks the beginning of the comment and */ marks the end of it. This type of comment can also be added in the middle of a line. They are widely used for elements such as to-do lists and copyright information. This is an example:

	/*Lorem ipsum
	The quick brown fox
	Jumped over the lazy dog */

As you may have noticed, this kind of comment did appear in our Main class. However, it looks a bit different. This is because it is a Javadoc comment, which will be covered later.

	/**
	 * @author WikibooksOverlord
	 */

Sometimes, we need to 'hide' some code temporarily. This can be achieved turning code into comments. This technique is known as commenting out.

How does Flash actually work?[edit]

What are integrated development environments?[edit]

The .as file we created above was just a text file; it didn't do anything constructive for us. To get the program to work, we need a compiler. Before getting to compilers, let's look at the different integrated development environments (IDEs) for coding in ActionScript. Although you can use a text editor to code in ActionScript and feed it into a command-line compiler, it is not recommended to do so. An integrated development environment typically contains the following features:

  • A project management system that organises the resources and files the project uses.
  • Syntax highlighting is a feature in which different parts of code are coloured to improve code readability. In this book, syntax colouring is achieved with the MediaWiki software.
  • Code hinting speeds up development by reminding you what you need to type next.
  • Syntax checkers which check your syntax.
  • A built-in compiler and debugging utility/debugger which allows you to compile and debug in the IDE. We will cover debuggers later.

A good IDE also provides features for the editing of related markup languages like MXML (which is outside the scope of this book but very helpful for ActionScript interfaces).

Common IDEs for Flash include:

  • Flash Professional: The first Flash authoring software, Flash Professional combines animation and coding into one piece of software. However, its IDE abilities are limited as a result. Flash CS3 and above supports AS3.
  • Eclipse: An all-purpose IDE used for many different languages, including ActionScript.
  • Flash Builder: A proprietory IDE based on Eclipse.
  • FlashDevelop: An open-source IDE geared towards ActionScript. It provides handy features such as SharedObject tracing and also contains advanced code hinting features.

In this book, we will provide instructions for FlashDevelop. If you use other IDEs, refer to the relevant documentation.

What is compilation?[edit]

Computers only understand machine language. ActionScript is a human-readable language, but not a computer-readable one. The more high-level a language is, the closer it is to the computer system. Machine code and assembly language are the lowest-level languages in that they boss around different parts of the computer system directly. Higher-level languages must be converted into lower-level languages for the computer to understand. A compiler is a program that converts code from a high-level programming language into a low-level language.

For ActionScript, it is a bit more complicated. An ActionScript compiler compiles our ActionScript into a lower-level language known as ActionScript Bytecode (ABC). Then, the ABC is wrapped together with the resouces (music, graphics, and so on) into another file known as a Shockwave Flash file (SWF), a magic performed by a SWF compiler. Flash Professional uses a SWF compiler called the Flash compiler, while FlashDevelop, Flash Builder, etc., use a SWF compiler called the Flex compiler.

The ABC is then executed by a runtime environment called Flash Player using the embedded resources. The runtime environment compiles the ABC into machine language that controls the computer's hardware. This conversion is performed in real time, and is known as just-in-time compilation.

There are two kinds of compilation, debug build and release build. Debug build is what you'll build during the development of your project. Once your project is ready for compilation, you will compile the release build, which is faster and more lightweight. To toggle between the builds, FlashDevelop has a toolbar on top with a drop-down menu that shows the tooltip 'Select Configuration' when you hover over it.

Let's do it![edit]

Now open the IDE of your choice and create a new project. In FlashDevelop, click on Project > New Project > AS3 Project. Name your project whatever you want. Now add the following folders to your project's main folder if they aren't already there:

  • src contains your project's source code.
  • bin contains your project's compiled binary (i.e. the SWF file if you've read the above section carefully).

Next, in the 'project' screen of your IDE, locate the Main class. If it isn't already there, create one. Copy the code above directly onto the text file. Set it as the document class (in FlashDevelop, right-click on the file in the Projects window and check 'Document class').

Now, set the compiler to compile to \bin\MyFile.swf (Project > Properties > Output in FlashDevelop). Now compile and run the project (CTRL + ENTER or the blue 'play' button in FlashDevelop).

If you've done everything correctly, you should see this in the output screen of your IDE:

Hello, world!
Your name is Daniel.

What happened just now?[edit]

Once a Flash application is started, the very first thing that happens is:

  1. A new instance of the document class is instantiated.
  2. The new instance is added to the stage.

Now, you may be completely confused. Don't let those new words intimidate you! We'll look at everything one by one.

Object instantiation[edit]

Let's say we now have a class called Apple. Fortunately, in the programming world, you don't need to take the time to grow the apple. All you need is to create an instance of the Apple class. To create 200 apples, create 200 intsances of the Apple class. The creation of an instance is called instantiation.

Usually, object instantiation is done using the new keyword. For example, the expression new Apple() instantiates a new apple. (Note that the round brackets here can be skipped.) However, our Main class here is a document class. That means the runtime environment very kindly instantiated the Main class for us.