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
TeacherandStudentare 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
Studentsimply stores aTeacherreference,assignedTeacher, alongside its ownname. - 3
showTeacher()reads that reference to print which teacher this particular student is associated with. - 4The same
Teacherobject could just as easily be referenced by several differentStudentobjects, since nothing here ties aTeacherto exactly oneStudent.
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