I have found some code that uses the virtual
keyword for functions, like:
package tryOut{
public class Parent {
public function Parent() {}
public function foo():void{
trace("Parent foo");
}//foo
public virtual function bar():void{
trace("Parent virtual bar");
}//bar
}//class
}//package
As far as I understand using the virtual
keyword should modify the way overriding a method works, or the way using a child method would work, or something. But it seems it does nothing at all. Having the extention:
package tryOut {
public class Child extends Parent {
public function Child() {}
public override function foo():void {
trace("Child foo");
}//foo
public override function bar():void {
trace("Child virtual bar");
}//bar
}//class
}//package
The following code prints:
var parent:Parent = new Parent();
var child:Child = new Child();
parent.foo(); //Parent foo
child.foo(); //Child foo
parent.bar(); //Parent virtual bar
child.bar(); //Child virtual bar
var childCast:Parent = child as Parent;
parent.foo(); //Parent foo
childCast.foo(); //Child foo
parent.bar(); //Parent virtual bar
childCast.bar(); //Child virtual bar
So both methods work the same regarding the override. Does the virtual
keyword changes something I am missing?
From the help documents (If you're using Flash, do a search for 'virtual'):
There are also several identifiers that are sometimes referred to as future reserved words. These identifiers are not reserved by ActionScript 3.0, though some of them may be treated as keywords by software that incorporates ActionScript 3.0. You might be able to use many of these identifiers in your code, but Adobe recommends that you do not use them because they may appear as keywords in a subsequent version of the language.
abstract boolean byte cast
char debugger double enum
export float goto intrinsic
long prototype short synchronized
throws to transient type
virtual volatile
So in AS3, virtual does absolutely nothing.
So both methods work the same regarding the override.
What makes you think that? The tests you've shown aren't comparable.
childCast
is typed as a Parent
, yet you still end up calling the function in Child
.
You don't check the same situation for the non-virtual method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With