In Java, aggregation is a form of composition, where one class contains references to other classes, but does not inherit from them. In other words, the aggregated classes are not part of the hierarchy of the aggregating class.
Aggregation is often used to model a “has-a” relationship between two classes. For example, a Person
class may have a reference to an Address
class, but the Person
class does not inherit from the Address
class. The Address
class can exist independently of the Person
class, and can be used by other classes as well.
Here’s an example of aggregation in Java:
class Address {
private String street;
private String city;
private String state;
private String zip;
// constructor and getters/setters omitted for brevity
}
class Person {
private String name;
private int age;
private Address address;
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
// getters and setters for name and age
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
In this example, the Person
class contains a reference to an Address
object, but does not inherit from the Address
class. The Address
class can be used by other classes as well, and changes to the Address
class do not affect the Person
class.
Aggregation is a powerful tool for building complex classes in Java, and can help to create more modular and reusable code. By using aggregation instead of inheritance, you can make your code more flexible and easier to maintain.