Pseudo-abstract classes in AS3

Tuesday, January 16th, 2007

I was developing an API which required specific abstract base classes to be developed in order to provide a default implementation for derived concrete classes, and, as you may know ActionScript 3.0 doesn’t support Abstract Classes (classes which can not be instantiated) so I had to develop my own solution that I thought I would share.

Abstract classes in general are classes which can not be instantiated directly, but rather would be used as a base class in which sub classes would provide a specific implementation. For example, a “Mammal” could be considered an abstract class as there are no concrete examples of a generic “Mammal” per say, but there are instances of it’s decedents; People, Dogs, Cats etc., which would more than likely also be abstract types themselves, however, eventually in the inheritance chain there would be concrete classes which would override the methods defined in the base class. The base class would provide a default implementation for it’s decedents but would also require that derived classes override methods which it can not provide a default implementation.

In ActionScript 3.0 you can not use the private access modifier in a constructor definition and ActionScript does not provide an actual abstract keyword, therefore you can not create a true abstract class.

So how do you create a “pseudo abstract class” in ActionScript 3? My solution is very simple:

In the above example all I am doing is creating an inner class: Private, which is only accessible from within the defined class Abstract. This enforces that only an object of type Private can be passed as an argument to the constructor.

Now were on to something. As you can clearly see from the example above, only a sub class of Abstract has access to an instance of Private via the protected static function getAccess(). Therefore only a sub class can instantiate an instance of Abstract, and why would it ever need to if it is a sub class? The sub class would then call super in the constructor and pass the instance of Private via getAccess(); as follows:

This is a pretty elegant solution in my book. Yes, it is obviously not an abstract class in the true sense of the word but it does the trick if you want to enforce that a class is never directly instantiated.

I would suggest restricting all Abstract classes access to internal if possible in order to help further avoid potential misuse by limiting access to package level classes only.

01.04.08 – I have since implemented a utility class for enforcing Abstract types which I recommend using over the implementation in this example. The AbstractEnforcer and examples can be found here

{ 2 comments to read ... please submit one more! }

{ 0 Pingbacks/Trackbacks }