Aggregation (HAS-A)
HAS-A relationship is based on usage, rather than inheritance. In other words, class A has-a relationship with class B, if code in class A has a reference to an instance of class B.
Example
class Student { String name; Address ad; }
Here you can say that Student has-a Address.
Student class has an instance variable of type Address. Student code can use Address reference to invoke methods on the Address, and get Address behavior.
Aggregation allow you to design classes that follow good Object Oriented practices. It also provide code reusability.
Example of Aggregation
class Author { String authorName; int age; String place; Author(String name,int age,String place) { this.authorName=name; this.age=age; this.place=place; } public String getAuthorName() { return authorName; } public int getAge() { return age; } public String getPlace() { return place; } } class Book { String name; int price; Author auth; Book(String n,int p,Author at) { this.name=n; this.price=p; this.auth=at; } public void showDetail() { System.out.println("Book is"+name); System.out.println("price "+price); System.out.println("Author is "+auth.getAuthorName()); } } class Test { public static void main(String args[]) { Author ath=new Author("Me",22,"India"); Book b=new Book("Java",550,ath); b.showDetail(); } }
Output :
Book is Java. price is 550. Author is me.
Q. What is Composition in java?
Composition is restricted form of Aggregation. For example a class Car cannot exist without Engine.
class Car { private Engine engine; Car(Engine en) { engine = en; } }
Q. When to use Inheritance and Aggregation?
When you need to use property and behaviour of a class without modifying it inside your class. In such case Aggregation is a better option. Whereas when you need to use and modify property and behaviour of a class inside your class, its best to use Inheritance.