Tuesday, October 12, 2010

Object Oriented Programming using Actionscript 3: Part 4

In this tutorial we will learn about another OOP concept - composition.

Composition is the ability to import classes into one class. In the last tutorial, we talked about inheritance - a boss is an employee, so is a janitor and so is an office worker. Composition works differently - say, you have 3 classes that you need to import into one.

A simple example would be: a computer has a system block, a monitor and a keyboard. Each component is a class here, and a computer is a class that consists of and works with these 3.

To import a class, write a line in your code just after your package definition:

// package info
import cl.kirill.Monitor();
// class info

Looks familiar? Yeah, it does - this is the same way we import built-in classes such as MovieClip, Buttons, Events, etc.

Let's create a Computer class now, that consists of SystemBlock, Monitor and Keyboard classes.

First of all, the SystemBlock.as:

package cl.kirill {
   public class SystemBlock
    {
     public function SystemBlock() {
       trace("System block is a part of this computer.");
     }
   }
  }

Monitor.as:

package cl.kirill {
   public class Monitor
    {
     public function Monitor() {
       trace("Monitor is a part of this computer.");
     }
   }
  }

And Keyboard.as:

package cl.kirill {
   public class Keyboard
    {
     public function Keyboard() {
       trace("Keyboard");
     }
   }
  }

Now, we need to create the main computer class. There are 2 things we need to do - first, to import the classes, and second, to create objects of these classes.

package cl.kirill
{
import cl.kirill.SystemBlock;
import cl.kirill.Monitor;
import cl.kirill.Keyboard;

public class Computer
{
public function Computer()
{
var mySB:SystemBlock = new SystemBlock();
var myM:Monitor = new Monitor();
var myK:Keyboard = new Keyboard();
}
}
}

And the code on the timeline (if you're using Flash):

import cl.kirill.Computer;

var myComp:Computer = new Computer();

Related:

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

No comments:

Post a Comment