Aggregation and Composition - OOPS
Sent by Copilot:
Sure! Let’s break down the concepts of aggregation and composition in Java with simple examples.
Aggregation
Aggregation is a type of association where one class contains a reference to another class. It represents a “has-a” relationship but with a weaker bond. The contained object can exist independently of the container object.
Example:
Consider a Library
and Book
:
class Book {
String title;
String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
}
class Library {
String name;
List<Book> books;
Library(String name, List<Book> books) {
this.name = name;
this.books = books;
}
void displayBooks() {
for (Book book : books) {
System.out.println("Title: " + book.title + ", Author: " + book.author);
}
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("To Kill a Mockingbird", "Harper Lee");
List<Book> books = new ArrayList<>();
books.add(book1);
books.add(book2);
Library library = new Library("City Library", books);
library.displayBooks();
}
}
In this example, Library
has a list of Book
objects. The Book
objects can exist independently of the Library
object.
Composition
Composition is a stronger form of association where one class contains another class, and the contained class cannot exist independently of the container class. It represents a “part-of” relationship.
Example:
Consider a House
and Room
:
class Room {
String name;
Room(String name) {
this.name = name;
}
}
class House {
String address;
List<Room> rooms;
House(String address) {
this.address = address;
this.rooms = new ArrayList<>();
rooms.add(new Room("Living Room"));
rooms.add(new Room("Bedroom"));
}
void displayRooms() {
for (Room room : rooms) {
System.out.println("Room: " + room.name);
}
}
}
public class Main {
public static void main(String[] args) {
House house = new House("123 Main St");
house.displayRooms();
}
}
In this example, House
contains Room
objects. The Room
objects cannot exist independently of the House
object. If the House
object is destroyed, the Room
objects are also destroyed.
Summary
- Aggregation: A “has-a” relationship with a weaker bond. The contained object can exist independently.
- Composition: A “part-of” relationship with a stronger bond. The contained object cannot exist independently.
Comments
Post a Comment