繁体   English   中英

继承抽象 Class 最终的属性

[英]Inheriting Abstract Class Attributes that are final

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

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) {
  }

}

问题:在子 class 中,我是否需要如下包含来自父 class 的最终属性,还是应该与子 class 中的上述构造相同? 或者,尽管大多数父属性是最终属性,子构造函数是否应该像下面这样同时保存父属性和子属性?

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

final 意味着它们不能被改变。 如果是这样的话,我怎么能把它应用到每个孩子 class 因为这些属性对于所有不同的子类都是通用的?

谢谢!

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

如果我们有:

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实例都有不同的值。

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

abstract class GroundVehicle {
  public final int wheelCount;
  protected GroundVehicle(int wheels) {
     wheelCount = wheels;
  }
}
class Car {
  public Car() { // no need for a parameter,
    super(4);    // we always have 4 wheels
  }
}
class Motorbike() {
   public Motorbike() {
     super(2);  // we do need to pass something though
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM