Java Association - The Coding Shala

Home >> Learn Java >> Java Association

Java Association

Association refers to the relationship between the classes using objects. Java association refers to how objects are related to each other and how they are using each other's functionality. Association can be one-to-one, one-to-many, many-to-one and many-to-many. Composition and Aggregation are the two forms of association. Association is best for code reusability when inheritance is not present.
Java Association - The Coding Shala

Example of Association in Java

The following example explains the Java Association:
//Example of Java Association

class Department{
    private String DeptName;
    
    Department(String name){
        this.DeptName = name;
    }
    
    public String getDeptName(){
        return DeptName;
    }
}

class Student{
    private String StudentName;
    
    Student(String name){
        this.StudentName = name;
    }
    
    public String getStudentName(){
        return StudentName;
    }
}

class Main{
    public static void main(String[] args){
        Department dp = new Department("Computer");
        Student st = new Student("Akshay");
        //now here student can use department name also 
        //this is a simple Example of Association
        System.out.println(st.getStudentName()+" is a student of "+dp.getDeptName()
                        +" department");
    }
}
Output:
Akshay is a student of Computer department

Here the Department can have many Students then this is a one-to-many relationship.

Composition and Aggregation are types of association, will see these in the following chapters.


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

InterviewBit - Colorful Number Solution - The Coding Shala