ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Inheritance | 31

Abstract classes and overriding inheritance


As you become familiar with design patterns, you’ll see more and more use of inter-


faces and its close cousin theabstract class. In ActionScript 3.0 the abstract class is a


little problematic because no class can be actually defined as abstract. While you can


use thepublicstatement to make a class public, ActionScript 3.0 (and ECMAScript)


chose not to include abstract classes in the language, as does Java.


However, you can create an abstract class in ActionScript 3.0. All you have to do is


create a regular class and treat it as an abstract class. Like interfaces, abstract classes


can have abstract methods that are not directly implemented. Rather, abstract classes


are subclassed and any abstract methods are overridden and implemented very much


like methods are in using interfaces. However, abstract classes can have implemented


methods as well; so when you need both abstract and implemented methods, abstract


classes are key to such design patterns as the Factory Method (Chapter 2), Decorator


(Chapter 4), and the Composite (Chapter 6), as well as others.


You know from inheritance that when one class subclasses another, the subclass


inherits the methods of the superclass. With an abstract class, you do not implement


the class but instead subclass it, and then implement the subclass and its methods.


Because of the abstract nature of at least some of the methods in the abstract class,


you mustoverridethem. Using theoverridestatement, an overridden class main-


tains its signature but can have its own unique details. You must be sure that the


name, number, type of parameters, and the return type are the same. In other words,


when you override a method from an abstract class, you treat the method exactly the


same as aninterface method.


Example 1-21 through Example 1-23 make up an application that illustrates how an


abstract class works. The abstract class has two methods; a concrete one and an


abstract one.


The subclass inherits the methods and interface from the abstract class, and it pro-


vides details for the abstract method by overriding it. However, the subclass leaves


the concrete class as is and does not attempt to instantiate the superclass.


Example 1-21. AbstractClass.as


package
{
//Abstract class
public class AbstractClass
{
function abstractMethod( ):void {}
function concreteMethod( ):void
{
trace("I'm a concrete method from an abstract class")
}
}
}

Free download pdf