3

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);
    }
}
Bono
  • 4,757
  • 6
  • 48
  • 77
  • Actually came across this question & answer later, which may be helpful to some: http://stackoverflow.com/questions/4090834/when-do-i-use-super-in-java – Bono Dec 17 '14 at 22:50

3 Answers3

7

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.

Manish Maheshwari
  • 4,045
  • 2
  • 15
  • 25
  • Perhaps "bad" was the wrong word to use, but since I've never seen it in actual use before I was wondering if I should really use it over regular setting. Thanks, the example is clear and logical too :) – Bono Dec 17 '14 at 21:55
1

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.

Dave
  • 591
  • 2
  • 13
0

For inheritence it's absolutly necessary. This is the reason, why abstract classes with different Constructers force you to implement all of them

wgitscht
  • 2,676
  • 2
  • 21
  • 25