Now I understand the theory of these types of associations:
- Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
- Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.
But it's difficult for me to understand how it works in practice.
So far this is my understanding and I would be glad if someone could correct me if I am wrong
// A simple separate class called Address
public class Address {
private String address;
public Address(String address) {
this.address = address;
}
}
// And a person class that has address field
public class Person {
private String firstName;
private String lastName;
private Address address;
}
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
....
}
I think this type of association is aggregation
because I have to set the address from client code so Address class hypothetically lives without a Person. Heres how it would look like:
public class Main{
public static void main(String[] args) {
Address address = new Address("308 Negra Arroyo Lane, Albuquerque, New Mexico");
Person person = new Person();
person.setAddress(address);
// address object still lives without person object and I can reuse it
}
}
On the other hand this seems like an composition
to me, since the Address class is instantiated within the Person class and it doesn't exist anywhere else (It's bound to one specific class)
public class Person {
private String firstName;
private String lastName;
private Address address;
public Person() {
address = new Address("308 Negra Arroyo Lane, Albuquerque, New Mexico");
}
public Address getAddress() {
return address;
}
....
}
And here's a client app
public class Main{
public static void main(String[] args) {
Person person = new Person();
person.getAddress();
// address object has no meaning outside of Person class
}
}
Atleast that's how I understand the concept, I may be wrong tho so I'd like if someone experienced could confirm this (or correct me if am wrong). Also the main reason why I do this is to write efficient UML so any thought of that would be appreciated too