Abstract Class in AS2.0

Page 1 of 1
Andrew Simmons
This user is yet to take control of their account and provide a biography. If you are the author of this article, please contact us via support AT actionscript DOT org.
View all articles by Andrew SimmonsWritten by: Andrew Simmons ,www.andrew-simmons.com andrew-simmons@andrew-simmons.com
Difficulty Level: advanced
Requirements: (MX 2004)
Topics Covered: OOP
Assumed Knowledge: Understanding of Interfaces in AS2.0
Unfortunately, abstract classes are not formally supported in ActionScript 2.0. However, remembering that interfaces are types, we may attain the full functionality of an abstract class.
Step One:
Create an interface that contains all the methods that would normally be abstract methods.
interface IAbstract
{
function myAbstractMethod();
}
Step Two:
Create the base class that will work as your abstract class. (The base class must cast a reference to itself as the interface type implemented by extending classes. See bellow.)
class Abstract
{
private var sub:IAbstract;
// Private constructor disallows instantiation
private function Abstract()
{
// Cast a reference of the extending class instance to the interface type
// which contains the abstract methods.
sub = IAbstract(this);
//Flash Player 7 Only
if(sub == null) // invalid cast will return null in Flash player 7
{
throw("Classes extending Abstract must implement IAbstract");
}
// end Flash Player 7 Only
/* For Flash Player 6 (or 7) use this runtime type check
if(!(sub instanceof IAbstract))
{
sub = null;
trace("Classes extending Abstract must implement IAbstract");
}
*/
//Because sub is of type IAbstract no compiler error is thrown
sub.myAbstractMethod();
}
}
Here is the foundation of this example. We store a reference to the current instance of the class extending Abstract in the variable sub .
sub = IAbstract(this);
This allows us to invoke the abstract method myAbstractMethod without a compiler error. If the extending class does not extend the interface, the cast returns null and we throw an exception. This forces the extending class to implement the interface IAbstract. The result is an uninstantiable class which contains some implementation and enforce specific and complete implementation by all deriving classes.
Step Three:
The extending class must simple extend the Abstract and implement IAbstract
class Extending extends Abstract implements IAbstract
{
// methods and properties here.
}
Spread The Word
Related Articles
1 Response to "Abstract Class in AS2.0" 
|
said this on 29 Sep 2007 7:02:03 PM CDT
public interface Moveable
{ public boolean canM public v public Location public interface Veh { p pu public vo } public cl { priv /** * Constructor for o */ public Loca { this.x this.y = y; } public int public void set public int g public void setY& } // end public abstr { public { } } public abst { public { su } } Part I You Add the rest of the clas F p { return false; } |



Author/Admin)