简体   繁体   中英

Inheriting Abstract Class Attributes that are final

I have a superclass that is Abstract and has the following attributes and constructor in it.

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

}

Question : in the child class, do I need to include the final attributes that are from the parent class as follows, or should it be the same as the above construct in the child class? Or, should the child constructor hold both the parent and child attributes as follows though most of the parent attributes are final?

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

Final means they can not be changed. If that is the case, how can I have it applied for each child class since the attributes are common for all the different child classes?

Thank you!

While all your child classes have the same parent class, this does not mean that an instance of a child class is sharing any of its member fields with any other object.

If we have:

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

Then each instance of A and B have their own field x and each instance can set it to a different value.

You can say:

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

and each of your objects has a different value for its instance of x .

About the part in my comment that you "don't need these parameters in the child constructor": it is possible that a subclass will always use the same value for that variable, in that case it doesn't need it be passed. For example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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