提问者:小点点

在子类[closed]中使用super时缺少Java属性


编辑问题以包括所需行为、特定问题或错误以及再现问题所需的最短代码。这将帮助其他人回答这个问题。

我正在创建一些飞行物体数组的 Java 代码,它们都有一个属性价格(双倍)。我对继承有点陌生,这是我第一次使用超级关键字。当我在数组中创建一个子类对象 Airplane 时,价格特征似乎没有正确通过构造函数。

以下是我的FlyingObject构造函数:

公共类 FlyingObject {

protected double price;

public FlyingObject()
{
    price = 0;
}

public FlyingObject(double aPrice)
{
    price = aPrice;
}

这是我的飞机构造函数:

// CONSTRUCTORS

public Airplane ()
{
    super();
    brand = "Unknown brand";
    horsepower = 0;
}

public Airplane (String aBrand, double aPrice, int aHorsepower)
{
    super(aPrice);
    brand = aBrand;
    horsepower = aHorsepower;
}

当我用参数字符串、双精度和int创建飞机时,字符串(品牌)和int(马力)都被正确注册,但价格保持在0。我做了什么明显错误的事情,我错过了吗?任何帮助都将不胜感激。

编辑:发现我做错了什么。愚蠢的错误。

在我的飞机类中,我将价格重新定义为一个实例变量,但忘记了它,它覆盖了 FlyingObject 的价格。

一旦我取出额外的价格变量并且只有价格变量来自超类(如预期的那样),那么一切正常。

下次会发布更好的示例(可重现)。干杯


共1个答案

匿名用户

我真的不确定你遇到的问题是什么。我刚刚在jshell中试用了它,看起来效果很好:

public class FlyingObject {
    protected double price;

    public FlyingObject() { price = 0; }

    public FlyingObject(double aPrice) { price = aPrice; }
}

public class Airplane extends FlyingObject {
    int horsepower;
    String brand;

    public Airplane() { 
        super(); 
        brand = "Unknown brand";
        horsepower = 0;
   }

   public Airplane(String aBrand, double aPrice, int aHorspower) {
        super(aPrice);
        brand = aBrand;
        horsepower = aHorsepower;
   }
}

如果我然后调用< code > plane plane = new plane(" Boeing ",500000,800);我得到一个飞机对象,其结果是< code>plane.price = 500000。

顺便说一句,您可能需要考虑(而不是aHorsepowera品牌等)仅在构造函数中使用horsepower品牌,然后使用this关键字,如下所示:

public Airplane(String brand, double price, int horsepower) {
    super(price);
    this.brand = brand;
    this.horsepower = horsepower;
}