AS3 是没有抽象类的,如果非要用抽象类的话,可以模拟出抽象类的特性。黑羽在编程之路中已经有了很好的解决方案,我在这里贴出来,给自己,也给需要的人指指路。
以下是三个重要的类的源码:
package com.mimswright.errors { /** * An error class used to ensure the correct behavior of asbsract classes. * * @author Mims Wright */ public class AbstractError extends Error { /** * Use this error in the constructor for your abstract class. */ public static const CONSTRUCTOR_ERROR:String="ERROR: An abstract class may not be instantiated."; /** * Use this error in abstract methods that should be overridden in your abstract class. */ public static const METHOD_ERROR:String="ERROR: Failed to implement an abstract method."; public function AbstractError(message:String="", id:int=0) { super(message, id); } } }
package com.mimswright.utils { import flash.utils.*; /** * Checks the class of <code>instance</code> against the <code>compareClass</code> for strict * equality. If the classes are exactly the same, returns true. If * the classes are different even if the <code>instance</code>'s class is a subclass * of <code>compareClass</code>, it returns false. * Does not work with interfaces. The compareClass must be a class. * * @author Mims Wright * * @example <listing version="3.0"> * var myBase:BaseClass = new BaseClass(); * var mySub:SubClass = new SubClass(); * trace(strictIs(myBase, BaseClass)); // true * trace(strictIs(mySub, SubClass)); // true * trace(strictIs(mySub, BaseClass)); // false * </listing> * * @param instance - the object whos class you want to check. * @param compareClass - the class to compare your object against. * @return true if instance is strictly of type compareClass. */ public function strictIs(instance:Object, compareClass:Class):Boolean { var instanceClass:Class=Class(getDefinitionByName(getQualifiedClassName(instance))); return instanceClass == compareClass; } }
package com.mimswright.utils { import com.mimswright.utils.strictIs; import com.mimswright.errors.AbstractError; public class AbstractEnforcer { public static function enforceConstructor(instance:Object, className:Class):void { if (strictIs(instance, className)) { throw(new AbstractError(AbstractError.CONSTRUCTOR_ERROR)); } } public static function enforceMethod():void { throw(new AbstractError(AbstractError.METHOD_ERROR)); } } }
应用:
package org.kingda.book.basicoop.abstractclassandinterface { import com.mimswright.utils.AbstractEnforcer; public class AbstractFoo { //抽象类的构造函数 public function AbstractFoo() { AbstractEnforcer.enforceConstructor(this, AbstractFoo); //trace ("ok"); } //抽象方法 public function hello():void { AbstractEnforcer.enforceMethod(); //trace ("hello()"); } } }