Does code in the constructor add to code in subclass constructors? Or does the subclass’s constructor override the superclass? Given this example superclass constructor:
class Car{
function Car(speed:int){
trace("CAR speed "+speed)
}
}
…and this subclass constructor:
class FordCar extends Car{
function FordCar(model:string){
trace("FORD model "+model)
}
}
When an instance of FordCar is created, will this trace “Car” and “Ford” ??
Edit: Will arguments also add up? See updated code above.
Yes. In most languages, the base class constructor is executed, then the subclasses constructor. This will make it trace: “CAR”, then “FORD”.
Both class constructors should always execute if you construct an instance of the subclass. Depending on the language in question, the actual execution and choice of base class constructor, including ordering, may be different. (This is particularly true in languages which allow for multiple inheritance – as the order of execution can be difficult to determine at first glance in some cases.)
Edit:
In most languages, your edited code will not compile. The subclass typically needs to pass arguments of the same type to the base class constructors. This is language specific, but often looks something like:
In some languages (mainly dynamic languages), the language will try to automatically convert, but you often may still need to specify which of the parent constructors to call.
Often, you can do: