Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Connect to objects using one call (Partner in Java)

I’m struggling with Java and need some help with 1-1 associations.
Sorry if I’m wording something wrong, I don’t know how to word it properly in English.

I want to connect both partner1 and partner2 using one call. Before the call, partner1 and partner2 is not connected, but after, they are. I can’t wrap my head around and have been stuck for hours.

Here is what I have so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Partner {

    private String name;
    private Partner partner;

    public String getName() {
        return this.name;
    }

    public Partner getPartner() {
        return this.partner;
    }

    public Partner(String name) {
        this.name = name;
    }

    public void setPartner(Partner person) {
        if (this == person) {
            throw new IllegalArgumentException("You can not marry yourself!");
        } else {
            this.partner = person;
        }

    }

    @Override
    public String toString() {
        return "Partner [name=" + name + ", partner=" + partner + "]";
    }

    public static void main(String[] args) {
        Partner p1 = new Partner("Mickey");
        Partner p2 = new Partner("Minnie");
        p1.setPartner(p2);
        System.out.println(p1.getPartner());
    }
}

>Solution :

You need to do the other association too, but don’t use person.setPartner(this) because it would call it then the other and you’ll go deep into recursion until a StackOverflowError

public void setPartner(Partner person) {
    if (this == person) {
        throw new IllegalArgumentException("You can not marry yourself!");
    } // else isn't mandatory as code execution whould stop if first branch taken
    this.partner = person;
    person.partner = this;
}

For the same reason, you may use partner.name. If you keep partner, it’ would call it’s toString which would call it’s partner toString , then road to StackOverflowError

@Override
public String toString() {
    return "Partner [name=" + name + ", partner=" + partner.name + "]";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading