Aggregation in Java

If a class contains another class or object of another class as its member then HAS-A relation is created between their class and their objects.

Aggregation represents part and whole relation between classes. It is weaker relation as both entity can exist independently.
For eg: Room has chairs, Room has tables.

Aggregation can be implemented by containing the object of a class as member of another class.

Lets take an example of Employee and Address classes to implement aggregation.
Here Address class object is a data member in Employee class.

JbkAddress.java

package com.javabykiran.aggregation;

public class JbkAddress {
    public String city;
    public String zipcode;
    public JbkAddress(String city, String zipcode) {
	super();
	this.city = city;
	this.zipcode = zipcode;
    }
}

JbkEmployee.java

package com.javabykiran.aggregation;

public class JbkEmployee {
    public int id;
    public String name;
    public JbkAddress address;
    public JbkEmployee(int id, String name, JbkAddress address) {
	super();
	this.id = id;
	this.name = name;
	this.address = address;
    }
    public void display() {
	System.out.println("Id -> " + id);
	System.out.println("Name -> " + name);
	System.out.println("City -> " + address.city);
	System.out.println("zipcode -> " + address.zipcode);
    }
}

JbkAggregationTest.java

package com.javabykiran.aggregation;

public class JbkAggregationTest {
    public static void main(String[] args) {
	JbkAddress jbkaddress = new JbkAddress("Pune", "411052");
	JbkEmployee jbkemployee = new JbkEmployee(1, "JavaBYKiran", jbkaddress);
	jbkemployee.display();
    }
}