Monday, October 11, 2010

Object Oriented Programming using Actionscript 3: Part 3

Today we will learn about one of the OOP concepts to use - inheritance.

Inheritance is a very common concept of OOP. It is the ability to inherit properties and methods of an existing class to create a new one, aka extend an existing class.

For example, we have an enemy which is based on the MovieClip class - it has a few frames of animation, but also methods that MovieClips normally don't have, such as attacking, jumping, etc. We are basically just extending the MovieClip class with new stuff. How do we do that? All we have to do is specify it in the line where we're creating our class:

// package info here
public class Enemy extends MovieClip {
// the rest of the class here

We can do this with our own classes, too. For example, we want to have Boss, OfficeWorker and Janitor classes. They are all employees and will all have a salary.

First we create our Employee class:

package cl.kirill {
   public class Employee {

     public var salary:Number;
     
     public function Employee() {
       trace("We have a new employee!");
     }
     }
  }

Now, the Boss:

package cl.kirill {
   public class Boss extends Employee {
     
     public function Boss() {
       salary=900
     }
     }
  }

OfficeWorker:

package cl.kirill {
   public class OfficeWorker extends Employee {
     
     public function OfficeWorker() {
       salary=600
     }
     }
  }

And Janitor:

package cl.kirill {
   public class Janitor extends Employee {
     
     public function Janitor() {
       salary=300
     }
     }
  }

Thanks for reading!

Related:

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

No comments:

Post a Comment