Relationships

  1. “Is-A” Relationship
    1. The “Is-A” relationship represents inheritance.
    2. It denotes that one class is a specialized form of another class.
    3. This relationship is established through inheritance, where the child class inherits the properties and behaviors of the parent class.
  2. “Has-A” Relationship
    1. The “Has-A” relationship represents composition.
    2. It denotes that a class contains one or more objects of another class.
    3. This relationship is established by including objects of one class as fields in another class.
    4. Relationship could be one to one, one to many & many to many.
  3. Association: Relationship b/w two different objects.
    1. Aggregation:
      1. It is a special type of association where one object contains another object.
      2. However, the contained object can exist independently of the container object, i.e., destroying one object will not destroy other object.
      3. It represents a “has-a” relationship but with more independence.
      4. Characteristics of Aggregation:
        • Weak relationship: The lifecycle of the contained object is not dependent on the container object.
        • Part-whole relationship: Represents a whole-part relationship where parts can exist independently of the whole.
class Library {
    private String name;
    private List<Book> books;
 
    public Library(String name) {
        this.name = name;
        this.books = new ArrayList<>();
    }
 
    // In composition, the Library creates the Book objects
    public void addBook(String title) {
        Book book = new Book(title); // Library creates the Book
        books.add(book);
    }
 
    public void displayBooks() {
        System.out.println("Library: " + name);
        for (Book book : books) {
            System.out.println("Book: " + book.getTitle());
        }
    }
 
    // In composition, the Library should also clean up (not strictly necessary in Java due to garbage collection)
    public void removeBook(Book book) {
        books.remove(book);
    }
}
 
class Book {
    private String title;
 
    // Private constructor to ensure that Books can only be created by the Library
    private Book(String title) {
        this.title = title;
    }
 
    public String getTitle() {
        return title;
    }
}
1. Composition:
	1. It is a stronger form of aggregation. 
	2. In composition, the contained object cannot exist independently of the container object. 
	3. If the container object is destroyed, the contained object is also destroyed.
	4. Characteristics of Composition:
		1. Strong relationship: The lifecycle of the contained object is dependent on the container object.
		2. Part-whole relationship: Represents a whole-part relationship where parts cannot exist independently of the whole.

Example of Aggregation:

Example of Composition: