views:

104

answers:

2

In AS3, if I have a class such:

public class dude
{
//default value for a dude
protected var _strength:Number = 1; 
public function dude( ):void
{    super( );
     //todo... calculate abilities of a dude based on his strength.
}
}

and a subclass

public class superDude extends dude
{

public function superDude( ):void
{
   _strength = 100;
   super( );
   trace( "strength of superDude: " + _strength );
}
}

This will trace strength of superDude is 1. I expected the variable I set in the subclass (prior to calling the superclass constructor) to remain.

Is there a way to assign class variables in subclass constructors which are not over-written by the superclass construtor? Or should I pass them up as constructor variables?

+3  A: 

You are calling super() after setting _strength to 100; this instruction is going to call the constructor from the super class which is going to change back _strength to 1 (the variable initialization happens in constructor). There is no way to prevent that and I think you should call super() before initializing the variables.

Cornel Creanga
+1  A: 

First off.. the default super class constructor (that does not take any parameters) is implicitly called from the subclass constructor. So you don't need to call it explicitly.

If the superclass constructor takes parameters in then you need to call it explicitly and that call must be the very first statement in the subclass constructor.

Kayes