×

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects in Java. It demonstrates how objects interact via communication and how they take advantage of the features and services offered by the other item. One-to-one, one-to-many, many-to-one, and many-to-many connections are all managed via association.

Examples for Association in Java

One to One

A student will have only one id which represents one to one relationship.

One to Many

A student can have multiple hobbies which represents one to many relationship.

Many to One

Students of all branches are related to one college which represents a Many to One relationship.

Many to Many

A student can access different teachers and one teacher can guide different students which represent a many-to-many relationship.

Program for Association in Java

Association.java

// Java example Program to explain the concept of Association
// Import required libraries
import java . io . * ;
import java .util . *;
// class with name branch is created
class Branch {
// instance variables of class 
private String name ;
// parameterized Constructor of this class
Branch ( String name )
{
// keyword this is used to refer to the current  class
this . name = name ;
}
// Method for the class
public String getBranchName ( )
{
return this . name ;
}
}
// class with name Student is created
class Student {
// instance variables of employee
private String name ;

Student ( String name )
{
// keyword this is used to refer to the current  class
this . name = name ;
}
// Method of Employee class
public String getStudentName ( )
{
// returning the name of employee
return this . name ;
}
}
class Main {
// Main  method
public static void main ( String [ ]  args )
{
    // using scanner class to read inputs from the user
    // Creating object for the scanner class
    Scanner sc = new Scanner ( System.in );
    // Asking the user to enter the branch name
    System.out.println("Enter branch name of the student ");
    // Storing the the string in variable s
    String s=sc.nextLine();
    // Asking the user to enter name of the student
    System.out.println("Enter name of the student ");
        // Storing the the string in variable s2
    String s2=sc.nextLine();
    // Object creation for classes 
Branch b = new Branch ( s ) ;
Student std = new Student ( s2 ) ;


        // Accessing methods of class using objects created for the class 
        
System . out . println ( std . getStudentName ( ) + " is student of "+ b . getBranchName ( ) ) ;
}
}

Output

Association In Java

Different types of Association

  • IS - A Association
  • HAS - A Association
    1. Aggregation
    2. Composition

IS – A Association

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Program for IS-A relation

IsARelation.java

// A example program to demonstrate IS – A relation
// importing necessary libraries
import java . io . *
// class with name student is created
class student{  
// instance variables are created inside the class 
// integer variable  is created with name  sal  and initialized to value 40000
 int sal = 40000;  
}  
// A class with the name IsARelation is created and using inheritance extending the properties of the parent class i.e ., student
class IsARelation extends student{  
// instance variable is created with name base and initialized to value 10000
 int base = 10000;  
 public static void main ( String args [ ] ) 
 {  
  IsARelation m = new IsARelation ();  
   System.out.println ( " Salary is: " + m . sal ) ;  
   System.out.println(" Base price is: " + m . base ) ;  
}  
}  

Output

Association In Java

HAS – A Association

HAS – A association is further divided into two types. They are aggregation and composition.

Aggregation

The HAS-A connection is defined in Java via the Aggregation association. The one-to-one or one-way connection is followed by aggregation. When two entities are included in an aggregate composition and one of the entities has an error, the other entity is unaffected.

Aggregation.java

import java . util . * ;   
import java . io . * ;
class Student    
{   
    String name;   
    int year ;   
    String course;   
        
    Student(String name, int year, String course )    
    {   
            
        this . name = name ;   
        this . year = year ;   
        this . course = course ;    
    }   
}   
class Subject   
{   
      
    String name ;   
    private List < Student > students ;   
    Subject ( String name , List < Student > students )    
    {   
            
        this . name = name ;   
        this . students = students ;   
            
    }  
    
}   


class College  
{   
        
    String Nameofcollege ;   
    private List < Subject > sub ;   
        
    College(String Nameofcollege, List<Subject> sub)   
    {   
        this.Nameofcollege = Nameofcollege;   
        this . sub = sub ;   
    }   
}    
// main method   
class Aggregation
{   
    public static void main ( String [ ] args )    
    {   
        Student s1 = new Student ( " Rohith ", 2002, " CSE " ) ;   
        Student s2 = new Student ( " Ram " , 2002, " ECE " ) ;   
        Student s3 = new Student ( " SAI ", 2003, " ECE " ) ;   
        Student s4 = new Student ( "Ravi " , 2000 , " CSE " ) ;   
        Student s5 = new Student ( " OM ",2002, " Mech " ) ;  
        //Constructing list of CSE Students. 
        List <Student> cse_students = new ArrayList < Student > ( ) ;   
        cse_students . add ( s1 ) ;   
        cse_students . add ( s4 ) ;   
        //Constructing list of ECE Students.   
        List < Student > ece_students = new ArrayList < Student > ( ) ;   
        ece_students . add ( s2 ) ;   
        ece_students . add ( s3 ) ;
        //Constructing list of Mech Students.   
        List <Student> mech_students = new ArrayList < Student > ( ) ;   
        mech_students . add ( s5 ) ;   
        Subject CSE = new Subject ( " CSE " , cse_students ) ;   
        Subject ECE = new Subject ( " ECe " , ece_students ) ;  
        Subject Mech = new Subject ( " Mech ", mech_students ) ;   
        List < Subject > sub = new ArrayList < Subject > ( ) ;   
        sub . add ( CSE ) ;   
        sub . add ( ECE ) ;  
        sub . add ( Mech ) ;   
        // creating object of College.   
        College college = new College("BVRIT", sub);   
        System . out . print ( " Number of students of 2nd year in the college "+ college . Nameofcollege +" are 1500" ) ;  
    }   
}  

Output

Association In Java

Composition

Composition is a constrained version of the aggregate in which the constituents are highly interdependent. Composition, as opposed to Aggregation, represents the part-of connection. When two entities are combined, the combined object can exist without the other entity, but when two entities are combined by composition, the composed object cannot exist.

Composition.java

import java . util . * ;  
class Mobiles 
{  
  public String name ;  
  public String ram ;  
  public String rom ;  
  Mobiles ( String Name , String ram , String rom )
  {  
    this . name = Name ;    
    this . ram = ram ;  
    this . rom = rom ;  
  }  
}  
class MobileShop  
{  
  private final List < Mobiles > mobiles ;  
  MobileShop ( List < Mobiles > mobiles )  
  {  
    this . mobiles = mobiles ;  
  }  
  public List < Mobiles > TotalMobileInShop ( ) {  
    return mobiles ;  
  }  
}  
public class Composition {  
  public static void main ( String [ ] args )  
  {  
    Mobiles m1 = new Mobiles ( " Iphone "," 12 GB ", " 256 GB " ) ;  
    Mobiles m2 = new Mobiles ( " One plus 10 T pro " , " 12 GB " , " 512 GB " ) ;  
    Mobiles m3 = new Mobiles ( " SAMSUNG S22 ultra " , "8 GB" , " 256 GB " ) ;  
    List < Mobiles > m = new ArrayList < Mobiles > ( ) ;  
    m . add ( m1 ) ;  
    m . add ( m2 ) ;  
    m . add ( m3 ) ;  
    MobileShop shop = new MobileShop ( m ) ;  
    List < Mobiles > mob = shop . TotalMobileInShop ( ) ;  
    for ( Mobiles mb : mob ) {  
      System . out . println ( " Name : " + mb . name + " RAM : " + mb . ram + " and "  + " ROM : " + mb . rom ) ;  
    }  
  }  
}  

Output

Association In Java

Related Topics

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.