Composition & Aggregation Relationship in Java

Introduction to Composition and Aggregation Relationship between Classes in Java

The composition relationship between classes in Java

A composition relationship between classes in Java is a relationship where one class contains another class as a member. This type of relationship is often used to model real-world relationships, such as the relationship between a car and its engine, or the relationship between a house and its rooms.

In a composition relationship, the lifetime of the contained class is tied to the lifetime of the containing class. This means that when the containing class is destroyed, the contained class is also destroyed.

Composition relationships can be implemented in Java using fields, methods, or both. For example, the following code shows a composition relationship between a `Car` class and an `Engine` class:


public class Car {
  private Engine engine;

  public Car() {
    this.engine = new Engine();
  }

  public Engine getEngine() {
    return engine;
  }

  public void startEngine() {
    engine.start();
  }
}

public class Engine {
  public void start() {
    System.out.println("Engine started!");
  }
}

In this example, the `Car` class has a field called `engine` that stores a reference to an `Engine` object. The `Car` class also has a method called `startEngine()` that starts the engine.

Composition relationships are a powerful tool for modeling real-world relationships in Java. By using composition relationships, you can write more robust and reliable code.

Here are some tips for using composition relationships effectively:

  • Use composition relationships to model real-world relationships where the lifetime of one class is tied to the lifetime of another class.
  • Avoid using composition relationships to model inheritance relationships.
  • Document the composition relationships in your code so that it is clear how the classes are related to each other.
Aggregation relationships in Java

Aggregation is a type of relationship between two classes in Java where one class contains a reference to another class. However, unlike composition, the lifetime of the contained class is not tied to the lifetime of the containing class. This means that the contained class can exist independently of the containing class.

Aggregation relationships are often used to model real-world relationships where the containing class needs to use the functionality of the contained class, but does not own or control it. For example, a student may have an aggregation relationship with a course. The student needs to use the functionality of the course to learn, but the student does not own or control the course.

Aggregation relationships can be implemented in Java using fields, methods, or both. For example, the following code shows an aggregation relationship between a `Student` class and a `Course` class:


public class Student {
  private Course course;

  public Student(Course course) {
    this.course = course;
  }

  public Course getCourse() {
    return course;
  }

  public void attendClass() {
    course.attendClass();
  }
}

public class Course {
  public void attendClass() {
    System.out.println("Attending class!");
  }
}

In this example, the `Student` class has a field called `course` that stores a reference to a `Course` object. The `Student` class also has a method called `attendClass()` that attends the class.

Aggregation relationships are a powerful tool for modeling real-world relationships in Java. By using aggregation relationships, you can write more robust and reliable code.

Here are some tips for using aggregation relationships effectively:

  • Use aggregation relationships to model real-world relationships where the containing class needs to use the functionality of the contained class, but does not own or control it.
  • Avoid using aggregation relationships to model inheritance relationships.
  • Document the aggregation relationships in your code so that it is clear how the classes are related to each other.

Exercises

Demo code for composition relationship in Java


  package sampleproject;
  import java.util.Scanner;
  
  public class democlass {
  
    public static void main(String[] args) {
      
      employee e = new employee("ram","123","sam","male");
        System.out.println(e.getInfo());	
    }
  }
  
  class employee
  {
    String name;
    String empid;
    dependent father;
  
    public employee(String iname,String iemp,String dname,String igender) {
        name=iname;
        empid=iemp;
        father = new dependent(dname,igender);
    }
    public String getInfo() {
            return(name+empid+father.dependentname+father.gender);		
    }
  }
  
  class dependent
  {
    String dependentname;
    String gender;
    protected String test;
    
      public dependent(String name, String gender) {
      this.dependentname = name;
      this.gender = gender;
    }
  
    public String getInfo() {
      // TODO Auto-generated method stub
          return(dependentname+gender);
    }
  } 

Create an employee class with the following fields
String name
String employeeId
address permanent (Here permanent is an object of type address).
The employee class has two methods
set_employee() - for setting employee details
get_employee() - for displaying employee details
The address class has the following data members and methods
String street;
String district;
String city;
String zipcode;
String country;
The methods for the address class is given below
set_address() - for setting the address details
get_address() - for getting the address details
Create an employee object and display the entire details of the employee object


  package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
        employee satish = new employee();
        satish.set_employee();
        satish.get_employee();
    }
}

class employee
{
	String name;
	String empid;
	address permanent;
	
	public void set_employee()
	{
		Scanner obj = new Scanner(System.in);
		System.out.println("Enter the employee name");
		this.name=obj.nextLine();
		System.out.println("Enter the employee id");
		this.empid=obj.nextLine();
		this.permanent = new address();
		this.permanent.set_address();
	}
	
	public void get_employee()
	{
		System.out.println(this.name+this.empid);
		this.permanent.get_address();
	}
}

class address
{
	String street;
	String district;
	String city;
	String zipcode;
	String country;
	
	public void set_address()
	{
		Scanner obj = new Scanner(System.in);
		System.out.println("Enter the street");
		this.street = obj.nextLine(); 
		System.out.println("Enter the district");
		this.district = obj.nextLine(); 
		System.out.println("Enter the city");
		this.city = obj.nextLine(); 
		System.out.println("Enter the zipcode");
		this.zipcode = obj.nextLine();
		System.out.println("Enter the country");
		this.country = obj.nextLine();
	}
	
	public void get_address()
	{
		System.out.println(this.street+this.district+this.city+this.zipcode+this.country);
	}
}

Output
Enter the employee name
Satish
Enter the employee id
123
Enter the street
sjt
Enter the district
vit
Enter the city
vellore
Enter the zipcode
632014
Enter the country
India
Satish123
sjtvitvellore632014India 

An object associated with an array of objects -
Create an employee class with the following fields
String name
String employeeId
address addarr[] (Here addarr is an array of objects of type address with size 2).
The employee class has two methods
set_employee() - for setting employee details
get_employee() - for displaying employee details
The address class has the following data members and methods
String street;
String district;
String city;

String zipcode;
String country;
The methods for the address class is given below
set_address() - for setting the address details
get_address() - for getting the address details
Create an employee object and display the entire details of the employee object. For the employee object the name, employee id and the details of the two address objects should be displayed


  package javaprogrammingdemo;
  import java.util.Scanner;
  public class javalabclass{
      public static void main(String args[]) 
      {
          employee satish = new employee();
          satish.set_employee();
          satish.get_employee();
      }
  }
  
  class employee
  {
    String name;
    String empid;
    address addarr[];
    
    public void set_employee()
    {
      Scanner obj = new Scanner(System.in);
      System.out.println("Enter the employee name");
      this.name=obj.nextLine();
      System.out.println("Enter the employee id");
      this.empid=obj.nextLine();
      addarr = new address[2];
      for(int i=0;i<addarr.length;i++)
      {
        addarr[i] = new address();
        addarr[i].set_address();
      }
    }
    
    public void get_employee()
    {
      System.out.println(this.name+this.empid);
      for(int i=0;i<addarr.length;i++)
      {
        addarr[i].get_address();
      }
    }
  }
  
  class address
  {
    String street;
    String district;
    String city;
    String zipcode;
    String country;
    
    public void set_address()
    {
      Scanner obj = new Scanner(System.in);
      System.out.println("Enter the street");
      this.street = obj.nextLine(); 
      System.out.println("Enter the district");
      this.district = obj.nextLine(); 
      System.out.println("Enter the city");
      this.city = obj.nextLine(); 
      System.out.println("Enter the zipcode");
      this.zipcode = obj.nextLine();
      System.out.println("Enter the country");
      this.country = obj.nextLine();
    }
    
    public void get_address()
    {
      System.out.println(this.street+this.district+this.city+this.zipcode+this.country);
    }
  }
  
  output
  Enter the employee name
  Satish
  Enter the employee id
  123
  Enter the street
  sjt
  Enter the district
  vit
  Enter the city
  vellore
  Enter the zipcode
  632014
  Enter the country
  India
  Enter the street
  thomas
  Enter the district
  guindy
  Enter the city
  chennai
  Enter the zipcode
  600025
  Enter the country
  India
  Satish123
  sjtvitvellore632014India
  thomasguindychennai600025India 

An array of objects where in every object in the array is associated with an array of objects
Create an employee class with the following fields
String name
String employeeId
address addarr[] (Here addarr is an array of objects of type address with size 2)
. The employee class has two methods
set_employee() - for setting employee details
get_employee() - for displaying employee details
The address class has the following data members and methods
String street;
String district;
String city;
String zipcode;
String country;
The methods for the address class is given below
set_address() - for setting the address details
get_address() - for getting the address details
Create an array of employee objects (consider 3 employee objects) and display the entire details for every employee object. For every employee object the name, employee id and the details of the two address objects should be displayed


  package javaprogrammingdemo;
  import java.util.Scanner;
  public class javalabclass{
      public static void main(String args[]) 
      {
          employee[] codespindle = new employee[2];
          for(int i=0;i<codespindle.length;i++)
          {
            codespindle[i]=new employee();
            codespindle[i].set_employee();
          }
          
          for(int i=0;i<codespindle.length;i++)
          {
            codespindle[i].get_employee();
          }
      }
  }
  
  class employee
  {
    String name;
    String empid;
    address addarr[];
    
    public void set_employee()
    {
      Scanner obj = new Scanner(System.in);
      System.out.println("Enter the employee name");
      this.name=obj.nextLine();
      System.out.println("Enter the employee id");
      this.empid=obj.nextLine();
      this.addarr = new address[2];
      for(int i=0;i<addarr.length;i++)
      {
        addarr[i] = new address();
        addarr[i].set_address();
      }
    }
    
    public void get_employee()
    {
      System.out.println(this.name+this.empid);
      for(int i=0;i<addarr.length;i++)
      {
        addarr[i].get_address();
      }
    }
  }
  
  class address
  {
    String street;
    String district;
    String city;
    String zipcode;
    String country;
    
    public void set_address()
    {
      Scanner obj = new Scanner(System.in);
      System.out.println("Enter the street");
      this.street = obj.nextLine(); 
      System.out.println("Enter the district");
      this.district = obj.nextLine(); 
      System.out.println("Enter the city");
      this.city = obj.nextLine(); 
      System.out.println("Enter the zipcode");
      this.zipcode = obj.nextLine();
      System.out.println("Enter the country");
      this.country = obj.nextLine();
    }
    
    public void get_address()
    {
      System.out.println(this.street+this.district+this.city+this.zipcode+this.country);
    }
  }
  
  output
  Enter the employee name
  Satish
  Enter the employee id
  123
  Enter the street
  sjt
  Enter the district
  vit
  Enter the city
  vellore
  Enter the zipcode
  632014
  Enter the country
  India
  Enter the street
  thomas
  Enter the district
  guindy
  Enter the city
  chennai
  Enter the zipcode
  600025
  Enter the country
  India
  Enter the employee name
  Ram
  Enter the employee id
  124
  Enter the street
  churchill
  Enter the district
  dallas
  Enter the city
  houston
  Enter the zipcode
  234
  Enter the country
  US
  Enter the street
  winston
  Enter the district
  florida
  Enter the city
  atlanta
  Enter the zipcode
  244
  Enter the country
  US
  Satish123
  sjtvitvellore632014India
  thomasguindychennai600025India
  Ram124
  churchilldallashouston234US
  winstonfloridaatlanta244US} 

Aggregation relationship between objects
Create an employee class with the data members and methods as shown below
String name;
String empid;
course courseassigned;
(here course assigned is an object of the course class)
public void set_employee(course c) (to set employee details)
public void get_employee() (to get employee details)
create a course class with the data members and methods as shown below
. String courseid;
String coursename;
public void set_course() - to set the course details
public void get_course() - to get the course details
The course class object should created first and assigned to the employee.Course and employee objects follow aggregation relationship.


  package javaprogrammingdemo;
  import java.util.Scanner;
  public class javalabclass{
      public static void main(String args[]) 
      {
        course java = new course();
        java.set_course();
        {
           employee satish = new employee();
           satish.set_employee(java);
           satish.get_employee();
        }
      }
  }
  
  class employee
  {
    String name;
    String empid;
    course courseassigned;
    
    public void set_employee(course c)
    {
      Scanner obj = new Scanner(System.in);
      System.out.println("Enter the employee name");
      this.name=obj.nextLine();
      System.out.println("Enter the employee id");
      this.empid=obj.nextLine();
      courseassigned = c;
    }
    
    public void get_employee()
    {
      System.out.println(this.name+this.empid);
      System.out.println(this.courseassigned.courseid+this.courseassigned.coursename);
    }
  }
  
  class course
  {
    String courseid;
    String coursename;
    
    public void set_course()
    {
      Scanner obj = new Scanner(System.in);
      System.out.println("Enter the courseid");
      this.courseid = obj.nextLine(); 
      System.out.println("Enter the coursename");
      this.coursename = obj.nextLine(); 
    }
    
    public void get_course()
    {
      System.out.println(this.courseid+this.coursename);
    }
  }
  
  output
  Enter the courseid
  103
  Enter the coursename
  Java
  Enter the employee name
  Satish
  Enter the employee id
  123
  Satish123
  103Java