Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 656
Bono Avatar asked Jan 23 '26 03:01

Bono


2 Answers

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.

like image 53
Manish Maheshwari Avatar answered Jan 25 '26 16:01

Manish Maheshwari


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 vehicles have a speed, which is defaulted to 0, but only car's have 4 wheels.

like image 45
Dave Avatar answered Jan 25 '26 16:01

Dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!