Sunday, October 10, 2010

Object Oriented Programming using Actionscript 3: Part 2

Today we will learn more about class construction and using methods.

In the last tutorial, we created a code that executes itself once the an instance of the class is created, because we put the code in the constructor function.

There are also methods. Those are the functions that we can call manually, or using an event listener.

For example (Greeter.as):

package cl.kirill
{
 public class Greeter
 {
  public function Greeter()
  {
  }
  public function say(txt:String):void
  {
  trace(txt);
  }
 }
}

And the main.fla:

import cl.kirill.Greeter;

var greeter:Greeter = new Greeter();

greeter.say("Hi everybody!");

As you can see, we left the constructor function empty, so nothing happens when we create the greeter variable. But now we can use the class's methods through greeter. We can pass parameters through it, etc.

Now you might wonder what do these "public" in front of variables and functions mean. Those words set the functions/methods access around your project. There are 4 types of these access modifiers:

public - allows access from anywhere (stage, any class)

internal - allows access from the same package

protected - allows access to subclasses

private - allows no external access (the variable/function can be only accessed in the class)

The default access modifier in Actionscript 3 is internal. Access modifiers of Classes can only be public or internal.

Now, let's turn what we now know about constructing classes into a simple scheme.



Thanks for reading!

Related:

Object Oriented Programming using ActionScript 3: Part 1
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