我不能使用super()在子类中创建2个超类对象;

c86crjj0  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(309)

我有一个超类“telefoon”(英语:telephone)。这个超类有一个子类“contactgevens”(egnlish contact data/user information)。这个子类'contactgevnes'也是子类/子类的一个超类,但与我的问题无关。
在超级班“telefoon”(电话)。

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.

子类/子类“contactgevens”。

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的对象,呈现'extends telefoon'无用。我能做一些像telefoon telefoon=super(//param here);?
还有,为什么我需要在telefoon中使用一个默认构造函数,否则在“contactgevens”的构造函数中示例化对象“telefoon”时会出错。

piztneat

piztneat1#

如前所述 ContactGegevens 类不应从继承 Telefoon ,因为它不满足继承的“is-a”逻辑。相反,它有多个电话号码。
但是考虑到你的操作限制,我建议你移除 telefoon 成员来自 ContactGegevens :它被继承替换。这给我们留下了:

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

相关问题