Should you use the superclass constructor to set the variables?

I somehow think it's a bad idea to do this. Is it common to this? I'm not sure about this because I have never seen it in practice as a real world example.

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);
    }
}

      

+3


source to share


3 answers


This is standard practice to use the superclass constructor. This allows code reuse when some validation on variables could have been done in the superclass constructor.

As an example, check out this code from the Apache Commons collection.



When used, super(..)

must be the first expression in the constructor of the child class.

+7




Consider the following:

public abstract class Vehicle {
    protected int numWheels;
    protected int speed;

    public Vehicle() {
        this.speed = 0;
    }
}

      

and



public class Car extends Vehicle {
     public Car() {
         super();
         this.numWheels = 4;
     }
}

      

All cars have a default speed of 0, but only the car has 4 wheels.

+1


source


This is absolutely necessary for inheritance. This is why, why abstract classes with different constructors force you to implement them all

0


source







All Articles