what is aggregation in java explain with an example
In Java, aggregation is a relationship between two classes where one class contains an object of another class. It is a specialized form of association where the child class (contained class) does not have its lifecycle controlled by the parent class (containing class). Aggregation represents a “has-a” relationship.
Here’s an example to help you understand aggregation in Java:
Let’s consider two classes: Author
and Book
. An Author
has multiple Book
objects. Here, Author
is the containing class, and Book
is the contained class.
/*
* Author: Zameer Ali
* */
// Author class
public class Author {
private String name;
private int age;
public Author(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters for name and age
// ...
}
// Book class
public class Book {
private String title;
private int ISBN;
public Book(String title, int ISBN) {
this.title = title;
this.ISBN = ISBN;
}
// Getters and setters for title and ISBN
// ...
}
// Aggregation example
public class BookStore {
private Author author;
private Book book;
public BookStore(Author author, Book book) {
this.author = author;
this.book = book;
}
public void displayBookInfo() {
System.out.println("Book Title: " + book.getTitle());
System.out.println("ISBN: " + book.getISBN());
System.out.println("Author: " + author.getName());
System.out.println("Author's Age: " + author.getAge());
}
public static void main(String[] args) {
Author author = new Author("John Doe", 35);
Book book = new Book("Java Programming", 1234567890);
// Creating a BookStore object using aggregation
BookStore bookstore = new BookStore(author, book);
bookstore.displayBookInfo();
}
}
In this example, the BookStore
class has objects of both Author
and Book
classes. The BookStore
class represents aggregation because it contains objects of other classes but does not control their lifecycle. The Author
and Book
classes can exist independently of the BookStore
class.