Search code examples
javainheritanceconstructorsuperclass

Should you use the superclass constructor to set variables?


I somehow think that doing this is a bad idea. Is it common to do this? I'm unsure of it's usage because I've never seen it in practice, as a real world example anyway.

public abstract class Car{
    protected int speed;

    public Car(int speed){
        this.speed = speed;
    }
}

public class Ambulance extends Car{
    public Ambulance(int speed){
        super(speed);
    }
}

Solution

  • It is a standard practice to use the superclass constructor. It allows code reuse, when some validations on the variables might have been done in the superclass constructor.

    As an example, check this code from Apache Commons Collection.

    When used, super(..) must be the first statement within the child class constructor.