Association


Association is a relation between two separate classes which establishes through their objects. Association can be one-to-one, one-to-many, many-to-one, and many-to-many. In OOP, an object communicates to other objects to use functionality and services provided by that object.

Composition and aggregation are the two forms of association. In the example below, two separate classes Bank and Employee are associated through their objects. Bank can have many employees, so it is a one-to-many relationship.

Association.java (association)
// Java program to illustrate the concept of association 
// Association between both the classes in main method
class Association {
  public static void main ( String[ ] args ) {
    Bank bank = new Bank( args[0] );
    Employee emp = new Employee( args[1] );
    System.out.println( emp.getEmployeeName( ) +
      " is an employee of " + bank.getBankName( ) );
  }
}  
// Class Bank
class Bank { 
  // Bank name
  private String name;    
  Bank( String name ) { this.name = name; }     
  public String getBankName( ) { return this.name; } 
}  
// Class Employee
class Employee { 
  // Employee name
  private String name;     
  Employee( String name ) { this.name = name; }
  public String getEmployeeName( ) { return this.name; }  
}
shell> java Association  (bank)   (employee)

Output:           Result:




      Mum’s the word.