Superclasses and Subclasses


Superclasses and subclasses come into play only when you borrow code from one class to run in another related class. The terminology can be confusing, so take a look at an example.

Imagine that you want to generate a random pair of numbers. You can create a class for this purpose, and then when you create an instance of it, you can invoke a method that generates a pair of random numbers.

class RandomPair{     // declare variables     var num1:Number;     var num2:Number;     // class constructor     function RandomPair(){     }     // define methods     function getRandomPair(){         num1 = Math.random();         num2 = Math.random();         var pair:Array = [num1, num2];         return pair;     } }


What if you need a pair of random numbers within a narrow range? You can create a subclass (RangeRandomPair) that extends the methods of the RandomPair class. The RangeRandomPair subclass has a method that calls the method from the superclass and tests the results to see whether the numbers are within the range you need. If the numbers don't meet the requirements, the internal superclass method is called again.

class RangeRandomPair extends RandomPair{     // declare variables     var upperLimit:Number;     var lowerLimit:Number;     // class constructor     function RangeRandomPair(upperLim, lowerLim){         upperLimit = upperLim;         lowerLimit = lowerLim;     }     // define methods     function getPair(){         var n1 = super.getRandomPair();         var n2 = super.getRandomPair();         if(n1 <= upperLimit && n1 >= lowerLimit                 && n2 <= upperLimit && n2 >= lowerLimit){             // numbers are both within range, return them             var pair:Array = [n1, n2];             return pair;         } else {             // numbers are not within range, try again             this.getPair();         }     } }


Although this case can be handled within a single class, this example should help illustrate the superclass and subclass relationships. Any class can be a superclass, and you can have a chain of superclass-subclass relationships. A subclass extends the code of a superclass to create a more specialized object.

To create a subclass of another class, use the extend keyword with the following syntax:

class SubClass extends SuperClass{     . . . }


Now that you've started to create relationships between classes and build structures of code, it's time to move on from class-based systems to explore the use of OOP logic to control events in movies.



Special Edition Using Macromedia Studio 8
Special Edition Using Macromedia Studio 8
ISBN: 0789733854
EAN: 2147483647
Year: 2003
Pages: 337

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net