Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Example of Association in Java
3.
Types of Association in Java
4.
One-to-One Association
4.1.
One-to-Many Association
4.2.
Many-to-Many Association
5.
Frequently Asked Questions
5.1.
What is the main advantage of using association in Java?
5.2.
Can an association be bidirectional in Java?
5.3.
How do you choose between different types of associations?
6.
Conclusion
Last Updated: May 7, 2024
Medium

Association in Java

Author Gaurav Gandhi
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

In Java, association is a relationship between two classes where one class uses the functionalities or services provided by the other class. It is a way to establish a connection between objects of different classes. Association helps in creating a structure where objects can interact with each other to achieve a specific functionality. 

Association in Java

In this article, we will learn the concept of association in Java, and understand its types, with proper examples.

Example of Association in Java

To illustrate association in Java, let’s consider a simple scenario involving two classes: Book and Author. In this relationship, an Author can write multiple Books, but each Book is written by only one Author. This example demonstrates a one-to-many association.

Here’s how you can implement this in Java:

class Author {
    String name;
    List<Book> books;
   Author(String name) {
        this.name = name;
        this.books = new ArrayList<>();
    }
    void addBook(Book book) {
        books.add(book);
    }
}

class Book {
    String title;
    Author author;

    Book(String title, Author author) {
        this.title = title;
        this.author = author;
    }
}


In this code:

  • The Author class has a name attribute to store the author’s name & a list of Book objects to represent the books written by the author.
     
  • The Book class has a title attribute for the book title & an author attribute linking back to the Author who wrote the book.


This setup allows us to manage books associated with their respective authors effectively. For example, to create an author and assign books to them, you could do the following:

public class Main {
    public static void main(String[] args) {
        Author author = new Author("J.K. Rowling");
        Book book1 = new Book("Harry Potter and the Sorcerer's Stone", author);
        Book book2 = new Book("Harry Potter and the Chamber of Secrets", author);
        
        author.addBook(book1);
        author.addBook(book2);
        
        System.out.println("Books written by " + author.name + ":");
        for(Book book : author.books) {
            System.out.println(book.title);
        }
    }
}


This code creates an Author object for J.K. Rowling and two Book objects. Each book is added to the list of books written by the author, demonstrating their association. When you run this program, it will display the titles of the books written by J.K. Rowling.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of Association in Java

Association in Java can be broadly classified into three types based on how classes are related and interact with each other: one-to-one, one-to-many, and many-to-many. Each type has its specific use cases and implementation methods.

One-to-One Association

In a one-to-one association, each instance of one class is associated with one instance of another class. For example, consider a scenario where each person has a unique driver's license. Here, a Person class and a License class would have a one-to-one relationship.

 

class Person {
    String name;
    License license; // each person has a unique license

    Person(String name, License license) {
        this.name = name;
        this.license = license;
    }
}

class License {
    String licenseNumber;
    Person person; // each license is assigned to a specific person

    License(String licenseNumber, Person person) {
        this.licenseNumber = licenseNumber;
        this.person = person;
    }
}

One-to-Many Association

A one-to-many association occurs when an instance of one class can be associated with multiple instances of another class. This was demonstrated in the earlier example where an Author can have multiple Books.

Many-to-Many Association

In a many-to-many association, multiple instances of one class can be associated with multiple instances of another class. For example, a Student class and a Course class where a student can enroll in multiple courses and each course can have multiple students.

class Student {
    String name;
    List<Course> courses; // students can enroll in multiple courses

    Student(String name) {
        this.name = name;
        this.courses = new ArrayList<>();
    }
    void enroll(Course course) {
        courses.add(course);
    }
}

class Course {
    String courseName;
    List<Student> students; // a course can have multiple students

    Course(String courseName) {
        this.courseName = courseName;
        this.students = new ArrayList<>();
    }

    void addStudent(Student student) {
        students.add(student);
    }
}

Frequently Asked Questions

What is the main advantage of using association in Java?

The main advantage of using association in Java is that it allows for flexible code where objects can remain independent yet collaborate. This increases reusability and modularity of the code.

Can an association be bidirectional in Java?

Yes, an association can be bidirectional, where both classes involved are aware of each other and can interact mutually. For example, in a many-to-many relationship between Student and Course, both classes can maintain a list of each other.

How do you choose between different types of associations?

The choice depends on the specific requirements of the application. One-to-one is used when objects directly correspond to each other, one-to-many for a single source managing multiple items, and many-to-many when the interaction is more complex involving numerous objects on both sides.

Conclusion

In this article, we have learned about the concept of association in Java and its practical applications through various types: one-to-one, one-to-many, and many-to-many. Understanding these relationships is crucial for designing effective object-oriented programs that are modular, maintainable, and scalable. We have also cleared every doubt with the relevant examples.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Previous article
Reverse the Number in Java
Next article
this Keyword in Java
Live masterclass