[英]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.