![](/img/trans.png)
[英]How can I insert code from subclass constructor in superclass constructor?
[英]How can I remove a parameter from a subclass constructor in Java?
在我的超類中,我定義了參數 a、b、c 和 d。 對於它的子類,我想刪除 d。 我有什么辦法可以做到這一點嗎?
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;
在我的子類中,我想創建一個沒有最后一個參數“thing”的構造函數
public class TypeBPrescription extends Prescription {
public TypeBPresciption(Medicine medicine, Doctor doctor, int patientID){
super(Medicine medicine, Doctor doctor, int patientID,)
}
}
像這樣寫給我的錯誤是子類 TypeBPrescription 中的構造函數未定義。 我希望子類沒有“東西”,但我希望我的超類擁有它。 有什么辦法嗎?
我會將默認值傳遞給超級 class。
public TypeBPresciption(Medicine medicine, Doctor doctor, int patientID){
super(medicine, doctor, patientID, 0)
}
向 super 添加多個構造函數以澄清thing
是可選的:
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;
}
然后子類可以使用適合其上下文的構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.