'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:
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());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
