超类构造函数的哪些参数?

时间:2012-09-25 14:12:56

标签: java inheritance

我正在研究java中与继承相关的一章,我有几个问题。

我已经基本了解了继承是如何工作的(覆盖方法,信息隐藏,如何使用子类中超类的私有字段等),但我只有一个问题,希望你能帮助我。

当超类具有非默认构造函数 - 没有参数时,这意味着在子类中我必须创建新的构造函数(它可以是默认的 - 没有参数),但在第一个语句中必须是超类构造函数调用

好的,到目前为止一切顺利。到目前为止我明白了。在子类中,您必须调用超类构造函数,匹配任何构造函数参数。

但是让我们检查以下代码:(超类)

public class Vehicle {

    private int numOfWheels;
    private double avgGallonsPerMile;   

    public Vehicle(int numOfWheels, double avgGallonsPerMile) {

        this.numOfWheels = numOfWheels;
        this.avgGallonsPerMile = avgGallonsPerMile;
    }
}

另一个子类代码:

public class Car extends Vehicle{

    public Car(double avgGallonsPerMile) {
        super(What should i write here?, avgGallonsPerMile);

        //force numOfWheels to 4;

    }   
}

以下是子类的练习:

每个子类 包含一个构造函数,它接受每加仑英里数值作为参数和 对于MotorCycle强制轮数为适当的值-2,为4 一辆车。

在子类构造函数中,我不需要 numOfWheels字段,因为无论如何我将强制它为4(对于汽车)和2(对于摩托车)。

但是我仍然需要超类的数据。从哪里获取数据?什么应该作为第一个参数调用超类构造函数。

但这仍然不是孤独的情况。我有很多练习,我不需要子类构造函数中的某些数据作为参数,但仍然需要它们在超类构造函数调用中。

在这种情况下我该怎么办?

我真的希望你理解我,我想说的。这有点难。

3 个答案:

答案 0 :(得分:2)

如果它无论如何都是相同的4用于汽车和2用于摩托车比制造如果修复!

super(4, avgGallonsPerMile);

或更好的方式 - 声明一个常量:

private static final int NUM_OF_WHEELS = 4;
..
super(Car.NUM_OF_WHEELS, avgGallonsPerMile);

答案 1 :(得分:2)

如果你不需要超级类中的某个领域,那么它很可能不应该存在。相反,您可以执行以下操作。

public abstract class Vehicle {
    private final double avgGallonsPerMile;

    public Vehicle(double avgGallonsPerMile) {
       this.avgGallonsPerMile = avgGallonsPerMile;
    }
    public double getAvgGallonsPerMile() { return avgGallonsPerMile; }
    public abstract int getNumOfWheels();
}

public class Car extends Vehicle{
    public Car(double avgGallonsPerMile) {
       super(avgGallonsPerMile);
    }
    public int getNumOfWheels() { return 4; }
}

public class Bicycle extends Vehicle{
    public Bicycle (double avgGallonsPerMile) {
       super(avgGallonsPerMile);
    }
    public int getNumOfWheels() { return 2; }
}

public class Tricycle extends Vehicle{
    public Tricycle (double avgGallonsPerMile) {
       super(avgGallonsPerMile);
    }
    public int getNumOfWheels() { return 3; }
}
顺便说一句:如果每英里燃油使用加仑,那么你的汽车效率必须非常低。

答案 2 :(得分:1)

非常简单:如果Car上的车轮数总是4,则只需传递值4:

public Car(double avgGallonsPerMile) {
   super(4, avgGallonsPerMile);

    // ...
}
相关问题