AS3: Understanding the virtual keyword
UPDATE: A diligent reader pointed out that current AS3 compilers ignore the virtual keyword all together and my code example does not work. All things point to the virtual keyword being a placeholder for future compiler support from Adobe. However, the principle outlined below should be a sound explanation of the expected behavior of the virtual keyword, and hopefully Adobe will add this support soon.
Recently I was given a unique challenge of making multiple derived classes of a base class, but cast the derived class as the base class in any and all usage. This poses a unique problem where I want to call methods against the super class, but execute the code found in the derived class.
In AS3 (and most other OOP languages), if you recast your object as a base class and try to execute a method that you overrode in your derived class, it will not execute your code. Lame! However there is an easy fix for this, and just something to keep in mind if you ever want to do Factory patterns. Simply use the virtual keyword when defining the base class’s function. This will tell the compiler to route the code execution path to the derived class’s “override” function declaration in the case that your derived class is recast as it’s base.
Here’s a code illustration (more or less AS3 pseudocode, for illustration only):
public class BaseClass {
public virtual function method () : void
{
trace("virtual keyword not present");
}
}
public class SuperClass extends BaseClass {
public override function method () : void
{
trace("virtual keyword present");
}
}
var myClass:SuperClass = new SuperClass();
var myCastClass:BaseClass = myClass as BaseClass;
myCastClass.method();
The output should should show the following text:
virtual keyword present
By removing the virtual keyword, the output should be:
virtual keyword not present