继承最终的抽象类属性

时间:2021-01-29 21:45:37

标签: java inheritance abstract-class

我有一个抽象的超类,其中包含以下属性和构造函数。

public abstract class Equipment {

  public final String serialNumber;

  public final String brand;

  public final String model;

  public final float equipmentPrice;

  public final Integer equipmentStatus;

  public float transactionPrice;

  
  public Equipment(String serialNumber, String brand, String model, float equipmentPrice, Integer equipmentStatus, float transactionPrice) {
  }

}

Child class:

public class Treadmill extends Equipment {

  public double maxSpeed;

  public Treadmill(Integer equipmentStatus, float transactionPrice, double maxSpeed) {
  }

}

问题:在子类中,我是否需要包含来自父类的最终属性,如下所示,还是应该与子类中的上述构造相同?或者,尽管大多数父属性都是最终的,但子构造函数是否应该按如下方式同时保存父属性和子属性?

public Treadmill(String serialNumber, String brand, String model, float equipmentPrice, Integer equipmentStatus, float transactionPrice, double maxSpeed) {
  }

Final 表示无法更改。如果是这种情况,由于属性对于所有不同的子类都是通用的,我如何将其应用于每个子类?

谢谢!

2 个答案:

答案 0 :(得分:0)

虽然您的所有子类都具有相同的父类,但这并不意味着子类的实例与任何其他对象共享其任何成员字段。

如果我们有:

class P {
  final int x;
  P(int x) {
    this.x = x;
  }
}

class A extends P {
  A(int x) {
    super(x);
  }
}

class B extends P {
  B(int x) {
    super(x);
  }
}

然后 A 和 B 的每个实例都有自己的字段 x,每个实例可以将其设置为不同的值。

你可以说:

  ...
  A a = new A(1);
  A aa = new A(2);
  B b = new B(3);
  // and also
  P p = new P(4);
  ...

并且每个对象的 x 实例都有不同的值。

答案 1 :(得分:0)

关于我的评论中您“在子构造函数中不需要这些参数”的部分:子类可能始终对该变量使用相同的值,在这种情况下它不需要它通过。例如

Traceback (most recent call last):
  File "D:/Dev/python/scratch/subclass_exception.py", line 13, in <module>
    raise HTTPExceptions.subclasses['Error501']
__main__.Error501