Abstract Classes in Flex

I recently found the need to implement an Abstract Class in a package I was writing for an SDK. When I searched out the methods that others had used in an attempt to “fake” an Abstract Class I felt they fell short. Most of the other solutions involve protecting the constructor of the Abstract Class so that it may only be instantiated by a child class. That’s pretty close, but what those solutions left out was the ability to defined abstract properties and functions. Here’s what my solution looks like:

The Abstract Class:

package abstractclass.exanple
{

import abstractclass.util.AbstractClassUtils;
import flash.utils.describeType;

public class ExampleAbstractClass
{

 public function ExampleAbstractClass() {
    AbstractClassUtils.enforceAbstractClass(
           this, ExampleAbstractClass,
         AbstractDefinitions);
 }

}
}

import mx.controls.Button;
import mx.core.UIComponent;

class AbstractDefinitions {

   public static var THIS_STATIC_PROPERTY:UIComponent;
   public var thisNonStaticProperty:String;

   public static function test(name:String, val:int=0) : int {return 0}

   public function nonStatic(blah:Button) : UIComponent {return null}

}

As you can see, the abstract properties and methods are defined in an inner class called AbstractDefinitions. These definitions are enforced by the call to AbstractClassUtils.enforceAbstractClass() in the constructor. Any sub classes are forced to implement these properties and methods.

How it works… The utility class uses introspection to ensure that the Objects are defined correctly. Introspection can be a fairly expensive operation, so use this method with care. You can always removed the enforceAbstractClass call when you put the code into production.

If you’d like to use this technique in your own apps, you can download my utility here: abstractclass.swc.

One thought on “Abstract Classes in Flex

  1. Anonymous

    Could you provide the code to your utility class so we’re able to understand the cost of your solution?

    Also, you mention the usage of an inner class – but – it looks like this is just a separate class… Not a proper inner class.

    A bit more description and source would be very helpful in assisting those of us trying to understand your thinking.

Comments are closed.