Beginner question about Super()


(Stop dreaming, Start living.) #1

I started out learning AS3 and FlashPunk 2 days ago. Now after following some tutorials and started creating my own game, I noticed after overriding a function like init, begin, update the auto function adds something inside that override function: super.funcname()

In a lot of tutorials I do not see this or sometimes they do have it. My question: is this a requirement everytime you override? what does it actually do because it seems not to make any difference if I remove it or not. And also what would be the correct place for it? above my code or under my code that I write within that override function?

Thank you in advance.


(Justin Wolf) #2

Calling super() on a function that you’ve overridden will simply also perform whatever code you have in the original function. For example:

/** Base function. */
public function traceStuff():void
{
     trace("Hello!");
}

/** Overridden function in another class. */
override public function traceStuff():void
{
     trace("Stuff");
     super.traceStuff();
}

Having the super.traceStuff() in the overridden function will still trace “Hello” as well as “Stuff” whenever you call the overridden function. However, if you remove the super.traceStuff(), it only performs actions inside your overridden function and nothing from the base function, therefore only tracing “Stuff”. So really, it’s up to you whether or not you call super() on functions or not.

Where you place the super() depends on when you want the base function’s code called in relation to when your overridden function’s actions perform. So in the above example, trace("Hello") would perform after trace("Stuff").

Keep in mind, some functions in FlashPunk actually require you to call super(). For example, your World update function will require the super.update() so that the base World class actually gets updated, which in turn updates all your entities. Functions like added and removed will not require a super() call because their original functions simply don’t contain any actions (unless of course you’ve added your own to them inside the FlashPunk source).


(Ultima2876) #3

It’s generally a good idea to get into a habit of doing super.xxx every time you override a function unless you have a specific reason not to.


(Stop dreaming, Start living.) #4

Thanks guys, that cleared things up.


(Zachary Lewis) #5

Here’s some reading for extra credit.

http://www.emanueleferonato.com/2009/08/10/understanding-as3-super-statement/