簡體   English   中英

我無法使用 super() 在子類中的超類之外創建 2 個對象;

[英]I Can't create 2 objects off superclass in subclass using super();

我有一個超類“電話”(英語:電話)。 這個超類有一個子類/子類“ContactGegevens”(英語聯系數據/用戶信息)。 這個子類“ContactGegevnes”也是子類/子類的超類,但與我的問題無關。

在超級班“電話”(電話)中。

public class Telefoon {

//Properties.
private String soort; //Enlgish = Type (Mobile or landline)
private String nummer; //English = Number (Just the number).

//Getters and Setters.
//Just normal getters and setters of all properties. not relevant to show here.    

//Constructors.
public Telefoon(String soort, String nummer) {
    this.nummer = nummer;
    this.soort = soort;
}

/** This constructor does nothing but when I don't have this one it gives and error in the child 
class??? */
public Telefoon() {
    this.nummer = "000000000";
    this.soort = "vast";
}

//Methods.
//Not relevant for question.

子類/子類“ContactGegevens”。

public class ContactGegevens extends Telefoon {

//Properties.
private String eMail;         //Email.
private Telefoon telefoon;    //Landline number.
private Telefoon gsm;         //Mobile phone number.

//Getters and Setters.
//Getters and Setters of all 3 properties. irrelevant to show here

//Constructors.
public ContactGegevens(String vast, String mobiel, String eMail) {
    /**
    *This works but in this case the 'extends Telefoon' is useless???!!
    As you can see I create 2 objects of superClass Telefoon. But then the 'extends Telefoon'
    is unnecessary, is there a Way i can do something like 

    telefoon = Super();
    gsm = Super(); 

    */
    telefoon = new Telefoon(vast,"vast");
    gsm = new Telefoon(mobiel, "mobiel");
    this.eMail = eMail;
}

//Methods.
public String toString() {
    return String.format("E-mail: %-15s %nTel: %-12s %nGSM: %-12s",eMail,telefoon.getNummer(), gsm.getNummer());
}

我的問題是“ContactGegevens”類擴展了 Telefoon 但是在 ContactGegevens 的構造函數中,我仍然必須創建 Telefoon 類的 2 個對象,使“Extends Telefoon”變得無用。 我可以做類似 Telefoon telefoon = Super(//Param here); 之類的事情嗎?

還有為什么我需要 Telefoon 中的默認構造函數,否則在“ContactGegevens”的構造函數中實例化對象“Telefoon”時會出錯。

如前所述, ContactGegevens類不應從Telefoon繼承,因為它不滿足繼承的“is-a”邏輯。 相反,它多個電話號碼。

但是考慮到您操作的限制,我建議從ContactGegevens刪除telefoon成員:它被繼承所取代。 這給我們留下了:

public class ContactGegevens extends Telefoon {
    private String eMail;         //Email.
    private Telefoon gsm;         //Mobile phone number.

    public ContactGegevens(String vast, String mobiel, String eMail) {
        super("vast", vast);
        this.eMail = eMail;
        gsm = new Telefoon("mobiel", mobiel);
    }

    public String toString() {
        return String.format("E-mail: %-15s %nTel: %-12s %nGSM: %-12s", eMail, getNummer(), gsm.getNummer());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM