你应该使用超类构造函数来设置变量吗?

Bon*_*ono 3 java inheritance constructor superclass

我不知何故认为这样做是个坏主意.这样做通常很常见吗?我不确定它的用法,因为我在实践中从未见过它,无论如何都是一个现实世界的例子.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Man*_*ari 7

使用超类构造函数是标准做法.当在超类构造函数中对变量进行某些验证时,它允许代码重用.

例如,从Apache Commons Collection中检查代码.

使用时,super(..)必须是子类构造函数中的第一个语句.