I have a base class “Vehicle” and a derived class “Car”.
package Game
{
public class Vehicle
{
public var myVar = "vehicle";
public function Vehicle()
{
trace("vehicle: " + myVar);
DoSomethingWithMyVar();
}
}
}
package Game
{
public class Car extends Vehicle
{
public function Car()
{
trace("car pre: " + myVar);
myVar = "car";
trace("car post: " + myVar);
super();
}
}
}
Basically, I want to set a vehicle property in Car’s constructor, call Vehicle’s constructor with super() and have Vehicle do something based on myVar. But this is the output i get:
car pre: null
car post: car
vehicle: vehicle
Why does myVar not keep the value of “car” when the base class constructor is called? How am I supposed to implement this correctly?
The variable initialization is in the super class. It won’t be initialized until you actually call
super();. This is why you should always callsuper()before doing anything else in the constructor. In fact, in some other languages, like Java, calls tosuper()are only allowed as the first statement within subclass constructors.However, you should consider using an initialization parameter in your constructor instead of setting the value in the declaration – it is the more elegant and maintainable way of doing what you intend to do.
resp.
plus, you can always call
new Car("Porsche");, or something like that 😉P.S. On a side note: Naming conventions in ActionScript recommend using names starting with a lower case letter for both packages and methods.