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)
01// Java program to illustrate the concept of association
02// Association between both the classes in main method
03class Association {
04  public static void main ( String[ ] args ) {
05    Bank bank = new Bank( args[0] );
06    Employee emp = new Employee( args[1] );
07    System.out.println( emp.getEmployeeName( ) +
08      " is an employee of " + bank.getBankName( ) );
09  }
10
11// Class Bank
12class Bank {
13  // Bank name
14  private String name;   
15  Bank( String name ) { this.name = name; }    
16  public String getBankName( ) { return this.name; }
17
18// Class Employee
19class Employee {
20  // Employee name
21  private String name;    
22  Employee( String name ) { this.name = name; }
23  public String getEmployeeName( ) { return this.name; } 
24}
shell> java Association  (bank)   (employee)

Output:           Result:




      Mum’s the word.