Home » Java Tutorial » Association in Java

Association in Java



Java

What is Association in Java

Association in java describes the relationship between two classes. It establishes relationships through their objects. An association may represent one-to-one, one-to-many, many-to-one, or many-to-many relationships. It enables the HAS-A relation between the classes.

Let’s see different examples of these association relations below.

  • A person can have only 1 driving license. This shows a one-to-one relation.
  • A person can have multiple bank accounts. This is a one-to-many relation.
  • Many employees can have a single reporting manager. This depicts a many-to-one relation.
  • Many students can have many teachers. This shows a many-to-many relation.

Before we see an illustration of association in java, it is important to have an understanding of the inheritance concept as well.

Example of Association in Java

This example shows a one-to-many relation where a single department can have many teachers. Although each class can exist separately, through association in java we can relate both the classes through their objects.

We create a Teacher class that contains names and subjects. We have 2 methods to retrieve the teacher’s name and subject. Through the constructor, we can set the name and subject respectively.

In Department class, we declare department name and list of teachers since this is an association of a one-to-many relation. Through the constructor, we initialize the department name, and using the getter method, we can get the department name.

Now, we need to have 2 other methods to get the list of teachers and to set the list of teachers. For this, we create getTeachers() and setDepartment(teachers).

READ  Dictionary in Java

Next, we create separate instances for both the classes and call the methods accordingly. Using ArrayList we can create a list of teachers and then pass this variable to the setDepartment to associate the teachers to a single department.

import java.util.ArrayList;
import java.util.List;

class Teacher {
  String name;
  String subject;
  
  Teacher(String name, String subject) {
    this.name = name;
    this.subject = subject;
  }
  
  public String getTeacherName() {
    return name;
  }
  
  public String getSubject() {
    return subject;
  }
  
  public String toString() {
    return name;
  }
  
}
public class Department {
  
  String deptname;
  List<Teacher> teachers;
  
  Department(String name) {
    this.deptname = name;
  }
  
  public String getDepartmentName() {
    return deptname;
  }
  
  public List<Teacher> getTeachers() {
    return teachers;
  }
  
  public void setDepartment(List<Teacher> teachers) {
    this.teachers = teachers;
  }

  public static void main(String[] args) {
    Department d = new Department("Computer Science");
    
    Teacher t1 = new Teacher("Shyamala", "Data Structures");
    Teacher t2 = new Teacher("Mohan","Networking");
    
    List<Teacher> teachers = new ArrayList<Teacher>();
    teachers.add(t1);
    teachers.add(t2);
    
    d.setDepartment(teachers);
    
    System.out.println(d.getTeachers() + " are the list of teachers in the Department " + d.getDepartmentName());
    System.out.println("Teacher details: ");
    System.out.println(t1.getTeacherName() + " " + t1.getSubject());
    System.out.println(t2.getTeacherName() + " " + t2.getSubject());
  }

}
[Shyamala, Mohan] are the list of teachers in the Department Computer Science
Teacher details: 
Shyamala Data Structures
Mohan Networking

Now that we have an idea of what is an association, let discuss the different forms of association in java.

Forms of Association

Association contains 2 different forms as mentioned below:

  • Composition
  • Aggregation

Association in Java

Composition

Composition denotes a belong-to or part-of type of association. In other words, we can say, one object contains or is composed of another object.  This implements a strong type of association which means that if the inner object cannot exist if the main outer object is destroyed.

For example, we cannot have a school without students. This means a school cannot exist without students in it. Hence it establishes a composition between school and students.

READ  Packages in Java

Another example is, we cannot have a car without an engine which means a car cannot move without an engine. Hence these two classes are tightly linked.

Features of Composition

  • Both classes are highly dependent on each other
  • The composition between 2 classes means both entities cannot exist without each other.
  • It implements a part-of relation.
  • It is a restricted form of aggregation.

Example of Composition

In the below example, we show the composition between Student and School. This means a school contains a list of students and if the school is destroyed then the student also does not exist. This is because, in the School constructor, we pass the Student list object as a parameter

import java.util.ArrayList;
import java.util.List;

//Student class
class Student {
  String studentname;
  int rollno;
  
  Student(String studentname, int rollno) {
    this.studentname = studentname;
    this.rollno = rollno;
  }
}

//School class which contains students
class School {
  private final List<Student> students;
  
  School(List<Student> students) {
    this.students = students;
  }
  
  public List<Student> getTotalNumberOfStudents() {
    return students;
  }
  
}
public class CompositionDemo {

  public static void main(String[] args) {
    Student s1 = new Student("Akash",100);
    Student s2 = new Student("Avinash",101);
    Student s3 = new Student("Balu",102);
    
    //Create list of students
    List<Student> students = new ArrayList<Student>();
    students.add(s1);
    students.add(s2);
    students.add(s3);
    
    School s = new School(students);
    List<Student> stu = s.getTotalNumberOfStudents();
    for(Student student: stu) {
      System.out.println("Student Name: " + student.studentname + " | " + " Roll No: " + student.rollno );
    }

  }

}
Student Name: Akash |  Roll No: 100
Student Name: Avinash |  Roll No: 101
Student Name: Balu |  Roll No: 102

Aggregation

Aggregation is also another form of Association that implements a HAS-A relationship and it supports only a unidirectional relation. This means one class has a reference to another class. For example, we can say that a person has an address. The reverse way i.e address has a person is not meaningful. This is why we say that it is a one-way relationship that is another form of association.

READ  Java Static Keyword

Example of Aggregation

class Address {
  String flatname;
  int flatno;
  String streetname;
  String area;
  String city;
  int pincode;
  
  Address(String name, int no, String streetname, String area, String city, int pin) {
    this.flatname = name;
    this.flatno = no;
    this.streetname = streetname;
    this.area = area;
    this.city = city;
    this.pincode = pin;	
  }
  
}
public class Person {
  String name;
  Address ad;
  
  Person(String name, Address ad) {
    this.name = name;
    this.ad = ad;
  }

  public static void main(String[] args) {
    Address ad = new Address("OakMont",10,"Maruthi nagar","Banaswadi","Bangalore",560072);
    Person p = new Person("Ravi",ad);
    System.out.println("Person Name: " + p.name);
    System.out.println("Address: ");
    System.out.println(p.ad.flatno + ", " + p.ad.flatname + ", " + p.ad.streetname);
    System.out.println(p.ad.area);
    System.out.println(p.ad.city + " - " + p.ad.pincode);

  }

}
Person Name: Ravi
Address: 
10, OakMont, Maruthi nagar
Banaswadi
Bangalore - 560072

Please refer to the Aggregation in Java tutorial to understand more about the aggregation concept.

Difference between composition and aggregation

Below are the differences between the two forms of association in java.

CompositionAggregation
Strong type of associationWeak type of association
Implements part-of or belongs-to relationshipImplements has-a relationship
Both classes are dependent on each other.
Child class cannot exist without parent class
Child class can exist independently even without parent class

 

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions

AD Blocker Detected !

Advertisements help running this website for free.

To view the content please disable AdBlocker and refresh the page.

Wait !!! You can Crack Technical Interviews of Companies like Amazon, Google, LinkedIn, Facebook, PayPal, Flipkart, etc

Anisha was able to crack Amazon after practicing questions from TutorialCup