Class Bootup
Being allowed to declare and define member variables all at once introduces a question: in which order does the class boot up? Further, if the class has parent classes, how does this change things? Read on for the simple results.
Consider the following test:
class Parent { public var log:Vector.<String>; public function appendLog(msg:String): int { if (!log) { log = new Vector.<String>(); } log.push(msg); return 0; } public var x:int = appendLog("x declaration"); public function Parent() { appendLog("Parent constructor"); } } class Child extends Parent { public var y:int = appendLog("y declaration"); public function Child() { appendLog("Child constructor"); } } var c:Child = new Child(); trace(c.log.join("\n"));
The output directly shows the order of execution:
y declaration x declaration Parent constructor Child constructor
The declarations are done in order from the bottommost class to the uppermost class and then the constructors are called from the bottommost class to the uppermost class. Knowing this will get you out of some sticky initialization problems. Thankfully, it’s simple to keep in mind. Have a great weekend!
#1 by Troy Gilbert on September 16th, 2009 ·
Constructors are actually called in the same order, from derived class to parent class. It’s just that the compiler puts the super() call in as the first instruction of the constructor if you don’t specify it yourself.
#2 by jackson on September 16th, 2009 ·
Yep, that’s exactly what it does. I intended this article to be more about the order of the direct field assignments, which was a mystery to me until I did these tests.