by Dinesh Thakur Category: Inheritance

Association is nothing more than  a connection that exists between two classes.  We use the objects of these classes to set up the connection. Association can be  done in three ways one-to-one, one-to-many and many-to-many. Let’s have a look at an example showing how association is implemented in Java.

public class InsuranceCompany {
    private String name;
    // insuranceCompany name
    InsuranceCompany(String name){
         this.name = name;
    }
    public String getInsuranceCompanyName(){
       return this.name;
    }
}
class Employee {
     private String name;
     Employee(String name){
          this.name = name;
     }
     public String getEmployeeName(){
         returnthis.name;
     }
}
class Association {
     public static void main (String[] args){
         InsuranceCompany insuranceCompany =new InsuranceCompany("DRPK");
         Employee emp =new Employee("Harry");
  System.out.println(emp.getEmployeeName()+" is an employee of "+ insuranceCompany.getInsuranceCompanyName());
    }
}

The output of this will be:  
  Harry is an employee of DRPK  
  In this example, our insurance company has a lot of employees and is connected to multiple objects. That makes this a one-to-many relationship.

Java Association Types

There are two types of association in Java:

Aggregation

• Aggregation is a special association type and it offers these characteristics:  
• Aggregation represents a HAS-A relationship  
• Aggregation is a unidirectional or one-way relationship  
• When you end one entity, it does not affect any others; they can all be independently present.  

Here’s an example:

import java.util.List;

class Employee {
    String name;
    int id ;
    String dept;
    Employee(String name,int id,String dept){
       this.name = name;
       this.id = id;
       this.dept = dept;
    }
}
class Department {
    String name;
    private List<Employee> Employees;
    Department(String name,List<Employee> Employees){
       this.name = name;
       this.Employees = Employees;
    }
    public List<Employee> getEmployees(){
       return Employees;
    }
}
class Branch {
     String branchName;
     private List<Department> departments;
     Branch(String branchName,List<Department> departments){
        this.branchName = branchName;
        this.departments = departments;
     }
     public int getTotalEmployeesInInstitute(){
         int noOfEmployees =0;
         List <Employee> Employees;
         for(Department dept : departments){
             Employees = dept.getEmployees();
             for(Employee s : Employees){
                   noOfEmployees++;
             }
         }
         return noOfEmployees;
     }
}
class GFG {
      public static void main (String[] args) {
          Employee s1 = new Employee("Dinesh",1,"CSE");
          Employee s2 = new Employee("Punar",2,"CSE");
          Employee s3 = new Employee("Sandeep",1,"EE");
          Employee s4 = new Employee("Rohit",2,"EE");
          List<Employee> cse_Employees =newArrayList<Employee>();
          cse_Employees.add(s1);
          cse_Employees.add(s2);
          List<Employee> ee_Employees =newArrayList<Employee>();
          ee_Employees.add(s3);
          ee_Employees.add(s4);
          Department CSE =new Department("CSE", cse_Employees);
          Department EE =new Department("EE", ee_Employees);
          List<Department> departments =newArrayList<Department>(); departments.add(CSE);
          departments.add(EE);
          Branch branch =new Branch("BITS", departments);
          int totalNumber =0;
          for(Department dep : departments)
          totalNumber += dep.getEmployees().size();
          System.out.print("Total number of Employees in the branch: ");System.out.print(totalNumber);
     }
}
The output of this will be:
the total number of Employees in the branch: 4

What we have here is a Branch which has several offices, such as EE, and CSE.  Each of the offices has several employees and we can use this to associate a  Branch to the class that references the object or objects in the Department class.  The implication is that the Branch class relates to the Department class via the objects. The Department class also references the one or more objects in the Employee class, the implication being there is a relationship with the Employee class  because of the objects.

Composition

We have already discussed the concept of inheritance which is a powerful mechanism of reusing code, minimizing data redundancy, and improving the organization of the object-oriented system. Inheritance is suitable only when classes are in a relationship in which subclass is a (kind of) superclass. For example, A Car is a Vehicle, so the class Car has all the features of class Vehicle in addition to the features of its class. However, we cannot always have a relationship between objects of different classes. For example, A car is not a kind of engine. To represent such a relationship, we have an alternative to inheritance known as composition. It is applied when classes are in a relationship in which subclass has a ( part of) superclass.

Unlike inheritance in which a subclass extends the functionality of a superclass, in composition, a class reuses the functionality by merely creating a reference to the object of the class it wants to reuse. For example, A car has an engine; a window has a button, a zoo has a tiger.
The following program segment creates a reference variable to an object of class x as a data member of class Y.

class X {............};
class Y {............ X x1,:// reference variable to object of class x............}

Here x1 reference variable of class x is contained within the class Y — the reference variable x1 used for accessing fields and methods of class x.
Now consider the following program that demonstrates the concept of composition.

//Use of composition
class Date {
    private int day;
    private int month;
    private int year;
    Date(int dd, int mm,int yy) {
       System.out.println("Constructor of Date class is called");
       day=dd; month=mm; year=yy;
    }
    public String toString() {
       return (day+"/"+month+"/"+year);
    }
}
class Employee {
    private int id;
    private String name;
    private Date hireDate;
    // object of Date class
    Employee(int num, String n,Date hire) {
       system.out.println("Constructor of Employee class is called");
       id=num ;
       name=n ;
       hireDate=hire;
    }
    public void display() {
        System.out.println("id ="+id) ;
        System.out.prin tIn ("Name= "+name) ;
        System. out.println ("Hiredate="+hireDate) ;
     }
}
public class Composition {
      public static void main (String[] args) {
          Date d = new Date(11,10,2012);
          Employee emp = new Employee (101, "Dinesh" ,d) ;
          emp.display () ;
      }
}
Output : Constructor of Date class is called Constructor of Employee class is called
id =101
Name=Dinesh
Hiredate=11/10/2012

Explanation: In this program, we first define a class Date for maintaining the date information.
Then we define a class Employee that not only contains members id, name, and display () but also contains a reference variable hireDate to refer objects of class Date as its member, which maintains employee's hire date.
The statement,
emp.display () ;
On execution display employee's id, name, and the hire date. The hire date is obtained with an implicit call to the Date class's toString () method.

Aggregation vs. Composition

• With aggregation, a child class can be independently present; this cannot  happen in composition because each entity requires the others to exist.  
• Aggregation is a HAS-A relationship while composition is a PART-OF relationship.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles