Association in Java with Example


< Previous Next >

OOPS Tutorial


In this article, we will learn the important object-oriented concept of Association.
It represents a relationship between two or more objects where all objects have their own life cycle and there is no owner. The name of an association specifies the nature of the relationship between objects.

1. Intent/Definition

It represents a relationship between two or more objects where all objects have their own life cycle and there is no owner. The name of an association specifies the nature of the relationship between objects.
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, many-to-many.
In Object-Oriented programming, an Object communicates to other Objects to use functionality and services provided by that object.
There are two forms of association
  1. Composition
  2. Aggregation

Let’s take an example of the relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.

2. Implementation

public class Teacher {
   private String name;
   private List<Student> students;
   // getter and setter methods 
}
public class Student {
   private String name;
   private List<Teacher> teachers;
   // getter and setter methods 
}

GitHub Repository

The source code of this post is available on GitHub: Object-Oriented Design Guide.
Learn complete Java Programming with Examples - Java Tutorial | Learn and Master in Java Programming with Examples

Related OOP Posts

Comments

  1. Hi where is the complete working example of association in java ?
    Do update this article !!!

    ReplyDelete

Post a Comment

Leave Comment