Understanding relationships between objects is a key concept in Object-Oriented Programming. In Java, two important relationships are Association and Composition. 🔹 Association represents a "Has-a" relationship where objects can exist independently. 🔹 Composition represents a "Part-of" relationship where the child object depends on the parent. Knowing the difference helps in designing clean, maintainable, and scalable applications. This infographic highlights the key differences, lifecycle, dependency, and examples to make the concept easier to understand. #Java #OOP #Programming #SoftwareDevelopment #JavaDeveloper #Coding #LearnJava
Composition : class Engine { String type; Engine(String type) { this.type = type; } } class Car { private final Engine engine; // Final often used to show strict dependency // Composition: The Engine is created inside the Car's constructor Car(String engineType) { this.engine = new Engine(engineType); } // The engine dies when the Car object is garbage collected } public class Main { public static void main(String[] args) { Car myCar = new Car("V8"); // No independent reference to Engine exists outside this Car instance } }
Aggregation // Contained class (can exist independently) class Book { String title; Book(String title) { this.title = title; } } // Container class class Library { private List<Book> books; // Aggregation: The list of books is passed from outside Library(List<Book> books) { this.books = books; } } public class Main { public static void main(String[] args) { Book b1 = new Book("Java Basics"); List<Book> bookList = new ArrayList<>(); bookList.add(b1); Library lib = new Library(bookList); // If lib is set to null, b1 still exists in bookList } }