Java ProgramsOOPAssociation

Association in Java

beginner·  OOP  ·  Relationships

Problem

Association is the most general relationship between two classes — one simply knows about or refers to the other, with no ownership or whole-part structure implied at all.

Model a Student that holds a reference to an assigned Teacher, where neither class owns or contains the other.

Input
new Student("Alice", teacher).showTeacher()
Output
Alice's teacher is Mr. Smith

Java Program

Java
class Teacher { String name; Teacher(String name) { this.name = name; } } class Student { String name; Teacher assignedTeacher; Student(String name, Teacher assignedTeacher) { this.name = name; this.assignedTeacher = assignedTeacher; } void showTeacher() { System.out.println(name + "'s teacher is " + assignedTeacher.name); } } public class AssociationDemo { public static void main(String[] args) { Teacher teacher = new Teacher("Mr. Smith"); Student student = new Student("Alice", teacher); student.showTeacher(); } }

Output

Alice's teacher is Mr. Smith

Core Logic

Giving Student a plain reference to a Teacher object models 'knows about', not 'is made of' — the two classes stay otherwise completely independent of each other.

How It Works
  1. 1Teacher and Student are two entirely separate classes — neither is defined in terms of the other, and neither contains a collection of the other the way a whole-part relationship would.
  2. 2Student simply stores a Teacher reference, assignedTeacher, alongside its own name.
  3. 3showTeacher() reads that reference to print which teacher this particular student is associated with.
  4. 4The same Teacher object could just as easily be referenced by several different Student objects, since nothing here ties a Teacher to exactly one Student.
Creating new Student("Alice", teacher) links Alice to Mr. Smith only through a stored reference, printed as "Alice's teacher is Mr. Smith".
💡

Key Point: Association doesn't imply a Student is 'made of' Teachers the way a Library is made of Books in composition or aggregation — it's just a reference between two otherwise unrelated, independently-meaningful classes.

Key Concepts

associationreference relationshipindependent classes

Related Programs