Wednesday, December 28, 2011

Abstract Class in AS3 - How To

Here is a hack for making an class that will function as an abstract class:
Cut and paste code below:
3 Files in code below:
[1]: The Base Abstract Class
[2]: The Sub Class that Extends the Abstract Class
[3]: .FLA file testing it.

ABSTRACT CLASS CODE:_________________________________________________

package com.JMIM02.ABS_TestAbstract{
    
    //Class Summary:
    //A test to see if I can make a TEST abstract class by simply throwing an ERROR in the constructor
    //Of the class that is an abstract class. Would only work if you DON'T need to call the superMethod
    //When using a class that extends this class.
    
    public class ABS_TestAbstract{

        protected var testVar:Number = 77;

        public function ABS_TestAbstract() {
            overrideToEmpty();
        }//[x]
        
        protected function overrideToEmpty():void{
            throw new Error("Abstract Class Cannot be instantiated by itself");
        }//[x]

    }//class
}//package


SUPERCLASS/SUBCLASS/DERIVED CLASS CODE:_______________________________

package com.JMIM02.Uses_TestAbstract{
    
    //Class Summary:
    //A test class that tests if I can make a "Pseudo Abstract Class"
    //By making the Base-Class's constructor throw an error.
    //This would prevent the class from being directly instantiated.
    
    import com.JMIM02.ABS_TestAbstract.ABS_TestAbstract;
    
    public class Uses_TestAbstract extends ABS_TestAbstract {

        public function Uses_TestAbstract() {
            testVar = 333;
            trace("testVar===" + testVar);
        }//constructor
        
        //make an empty function so that you can instantiate the base-class.
        protected override function overrideToEmpty():void{}//[x]
    }//class
}//package
 

.FLA FILE TESTING CLASS:______________________________________________

import com.JMIM02.Uses_TestAbstract.Uses_TestAbstract;
import com.JMIM02.ABS_TestAbstract.ABS_TestAbstract;

var inst:Uses_TestAbstract = new Uses_TestAbstract();

//block of code below WILL throw error since you cannot directly instance the base-class:
/*
var base:ABS_TestAbstract = new ABS_TestAbstract();
*/

No comments:

Post a Comment