Saturday, October 9, 2010

Object Oriented Programming using ActionScript 3: Part 1

Today we will learn about Object Oriented Programming in AS3.

OOP in Actionscript 3 means that you can create custom classes and use them in your games and applications. You create external .as files and then import them to Flash (that's if your using Adobe Flash, such softwares like FlashDevelop are fully Object Oriented). Using OOP, you will be able to create more complex games and manage them easier.

Classes are a collection of functions. They are the building blocks of your project. Each class has 2 types of functions: a constructor and methods. A constructor is a function that is called once a new instance of the class is created. A method is a normal function that is only executed when you call it.

Let's see it in action. Here is an example of a simple class (written in the Greeter.as file).

package cl.kirill {
   public class Greeter
    {
     public var greeting:String = "Hello";
     public function Greeter() {
       trace(greeting);
     }
   }
  }

In the first line, we create a package. A package is like a folder - it can contain many different classes that can cooperate with each other. In this example, I have the Greeter.as file in a folder called 'kirill', which is in a folder called 'cl'. The main .fla file I'm working with is located just outside the 'cl' folder, so that I can get to this Greeter class using 'cl.kirill'.


The next line is defining the class and setting it as public.

Then we have a function called Greeter. This has to have the same name as the class name. This function is a constructor, which, as stated before, is executed once a new instance of the class is created. We will trace "Hello" once we put the class in our flash.

But how do we put it in flash?

Firstly, you need to import the class. This is where you need to put the package name (one more time: package name = directory, where the .as file is located, relative to the main .fla).

import cl.kirill.Greeter;
var myGreeter:Greeter = new Greeter();

Now if we test our movie - it will output 'hello'.

Next time we will go deeper. Thanks for reading!

Related:

Object Oriented Programming using ActionScript 3: Part 2
Object Oriented Programming using ActionScript 3: Part 3
Object Oriented Programming using ActionScript 3: Part 4
Object Oriented Programming using ActionScript 3: Part 5

No comments:

Post a Comment