简体   繁体   中英

How can I remove a parameter from a subclass constructor in Java?

In my superclass, I have defined the parameters a, b, c and d. For its subclass, I want to remove d. Is there any way for me to do this?

abstract class Prescription {
    protected Medicine Medicine;
    protected Doctor doctor;
    protected int patientID, thing;
    public Resept(Medicine medicine, Doctor doctor, int patientID, int thing) {
        this.legemiddel = legemiddel;
        this.lege = utskrivendeLege;
        this.pasientID = pasientID;
        this.thing = thing;

And in my subclass, I would like to create a constructor without the last parameter "thing"

public class TypeBPrescription extends Prescription {
    public TypeBPresciption(Medicine medicine, Doctor doctor, int patientID){
        super(Medicine medicine, Doctor doctor, int patientID,)
    }
}

Writing it like this gives me the error that the constructor in the subclass TypeBPrescription is undefined. I want the subclass to not have "thing", but I want my superclass to have it. Is there any way to do this?

I would pass a default value to the super class.

public TypeBPresciption(Medicine medicine, Doctor doctor, int patientID){
    super(medicine, doctor, patientID, 0)
}

Add multiple constructors to the super to clarify thing is optional:

abstract class Prescription {
    private static final int DEFAULT_THING = 0;
    protected Medicine Medicine;
    protected Doctor doctor;
    protected int patientID, thing;

    public Prescription (Medicine medicine, Doctor doctor, int patientID) 
   {
    this(medicine, doctor, paitentId, DEFAULT_THING);


    public Prescription (Medicine medicine, Doctor doctor, int patientID, int thing) {
    this.legemiddel = legemiddel;
    this.lege = utskrivendeLege;
    this.pasientID = pasientID;
    this.thing = thing;
}

Then a sub-class can use whichever constructor fits their context.

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