Association: objects that work together
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A teacher teaches many students, and a customer pays a shop. The objects work together, yet none of them belongs to another. How do you show that in code?
What association means
Association is a relationship in which objects of one class know and use objects of another class, while each object lives on its own and neither one owns the other.
A teacher and a student both exist on their own: if the teacher leaves the college, the student does not disappear. In code, one class simply holds or receives a reference to the other.
class Student { private String name; private Teacher mentor; // a link through a field}
class Teacher { private String name;
void grade(Student s, int marks) { // a link through a parameter System.out.println(name + " grades a student: " + marks); }}There is no whole and no part here, just partners. Aggregation (opens in a new tab) and Composition (opens in a new tab) are special kinds of association that add a whole-part meaning.
Two ways to link: a parameter or a field
A parameter link is short: the object is passed into one method, used, and forgotten. A field link lasts: the object is stored and used again and again.
Example 1 · A parameter link: grading a student
class Student { private String name; private int marks;
Student(String name) { this.name = name; }
void setMarks(int marks) { this.marks = marks; } String describe() { return name + ": " + marks; }}
class Teacher { private String name;
Teacher(String name) { this.name = name; }
void grade(Student s, int marks) { s.setMarks(marks); System.out.println(name + " graded " + s.describe()); }}
public class GradeDemo { public static void main(String[] args) { Teacher t = new Teacher("Mrs. Iyer"); Student a = new Student("Aarav"); Student d = new Student("Diya"); t.grade(a, 78); t.grade(d, 91); }}Mrs. Iyer graded Aarav: 78 Mrs. Iyer graded Diya: 91
What this code does
grade(Student s, int marks)links the teacher to a student only during the call.Teacherhas noStudentfield.- The teacher tells the student to change,
s.setMarks(marks), instead of touching the student's field directly.
Example 2 · A field link: a student and a mentor
class Teacher { private String name;
Teacher(String name) { this.name = name; }
String getName() { return name; }
void answer(String doubt) { System.out.println(name + " explains: " + doubt); }}
class Student { private String name; private Teacher mentor;
Student(String name) { this.name = name; }
void setMentor(Teacher mentor) { this.mentor = mentor; }
void askDoubt(String doubt) { System.out.println(name + " asks " + mentor.getName()); mentor.answer(doubt); }}
public class MentorDemo { public static void main(String[] args) { Teacher t = new Teacher("Mr. Khan"); Student s = new Student("Rohan"); s.setMentor(t); s.askDoubt("recursion"); s.askDoubt("arrays"); }}Rohan asks Mr. Khan Mr. Khan explains: recursion Rohan asks Mr. Khan Mr. Khan explains: arrays
What this code does
- The student keeps the teacher in a field, so the link lasts. Both doubts go to the same mentor.
- The teacher was created outside and handed in with
setMentor. The student does not own the teacher.
Pick the parameter link when two objects meet only for one action, like grading. Pick a field when one object needs the other for most of its life, like a student and a mentor.
One-to-one and one-to-many
Multiplicity is how many objects can be on each side of a link. One-to-one means one object on each side (a student and one mentor); one-to-many means one object linked to many (a teacher and her students).
One-to-one needs a single field. For one-to-many without lists, keep the objects in a fixed-size array plus an int count of filled places: Student[] students = new Student[3];.
Example 3 · One-to-many: a teacher's batch
class Student { private String name;
Student(String name) { this.name = name; }
String getName() { return name; }}
class Teacher { private String name; private Student[] students = new Student[3]; private int count;
Teacher(String name) { this.name = name; }
void addStudent(Student s) { if (count == students.length) { System.out.println("Batch full, cannot add " + s.getName()); return; } students[count] = s; count++; }
void printBatch() { System.out.println(name + "'s batch (" + count + "):"); for (int i = 0; i < count; i++) { System.out.println("- " + students[i].getName()); } }}
public class BatchDemo { public static void main(String[] args) { Teacher t = new Teacher("Mrs. Rao"); t.addStudent(new Student("Aarav")); t.addStudent(new Student("Diya")); t.addStudent(new Student("Kavya")); t.addStudent(new Student("Arjun")); t.printBatch(); }}Batch full, cannot add Arjun Mrs. Rao's batch (3): - Aarav - Diya - Kavya
What this code does
- One teacher links to many students through an array and a
count. The checkcount == students.lengthstops the fourth student safely. - The loop runs to
count, notstudents.length, so it never touches an emptynullplace.
The pattern: check count < array.length, store at array[count], then count++. Loop up to count, never array.length, because the empty places are null, as in Many objects, references and null (opens in a new tab).
Two-way links, done carefully
A unidirectional association is a link only one side knows about, such as a student with a mentor field. A bidirectional association is known by both sides, so both sides must always be updated together.
The teacher keeps a list of students, and each student knows the mentor. If only one side is updated, the teacher says "Diya is mine" while Diya says "I have no mentor".
Example 4 · A two-way link set on one side only
class Teacher { private String name; private Student[] students = new Student[3]; private int count;
Teacher(String name) { this.name = name; }
String getName() { return name; }
void addStudent(Student s) { students[count] = s; count++; }
int getCount() { return count; }}
class Student { private String name; private Teacher mentor;
Student(String name) { this.name = name; }
void setMentor(Teacher mentor) { this.mentor = mentor; }
void showMentor() { if (mentor == null) { System.out.println(name + " has no mentor"); } else { System.out.println(name + "'s mentor: " + mentor.getName()); } }}
public class HalfLinkDemo { public static void main(String[] args) { Teacher t = new Teacher("Mr. Khan"); Student d = new Student("Diya"); t.addStudent(d); System.out.println(t.getName() + " mentors " + t.getCount() + " student(s)"); d.showMentor(); }}Mr. Khan mentors 1 student(s) Diya has no mentor
What this code does
- The teacher's array holds Diya, but nobody called
d.setMentor(t). The two sides now disagree. - No error appears; the data is just wrong. This is the classic bug with two-way links.
Example 5 · The fix: one method sets both sides
class Teacher { private String name; private Student[] students = new Student[3]; private int count;
Teacher(String name) { this.name = name; }
String getName() { return name; }
void addStudent(Student s) { if (count == students.length) { return; } students[count] = s; count++; s.setMentor(this); }
int getCount() { return count; }}
class Student { private String name; private Teacher mentor;
Student(String name) { this.name = name; }
void setMentor(Teacher mentor) { this.mentor = mentor; }
void showMentor() { System.out.println(name + "'s mentor: " + mentor.getName()); }}
public class TwoWayDemo { public static void main(String[] args) { Teacher t = new Teacher("Mr. Khan"); Student d = new Student("Diya"); t.addStudent(d); System.out.println(t.getName() + " mentors " + t.getCount() + " student(s)"); d.showMentor(); }}Mr. Khan mentors 1 student(s) Diya's mentor: Mr. Khan
What this code does
addStudentstores the student and callss.setMentor(this), handing the teacher itself to the student. Both sides are set in one place.setMentordoes not call back intoaddStudent. Only one side starts the update, so there is no endless loop of calls.
Let one method set both sides, and let only that side start the update. If addStudent calls setMentor and setMentor calls addStudent again, the two calls repeat until Java throws a StackOverflowError.
Objects working together on a job
Collaboration is two or more associated objects each doing the part of a task they know best, by calling each other's methods instead of changing each other's fields.
In a UPI payment, the app does not change balances itself. It asks the sender's account to take money out, and only if that works, asks the receiver's account to add it.
Example 6 · Collaboration: a UPI transfer
class Account { private String owner; private int balance;
Account(String owner, int balance) { this.owner = owner; this.balance = balance; }
String getOwner() { return owner; } int getBalance() { return balance; }
boolean withdraw(int amount) { if (amount <= 0 || amount > balance) { return false; } balance = balance - amount; return true; }
void deposit(int amount) { balance = balance + amount; }}
class UpiApp { void send(Account from, Account to, int amount) { if (from.withdraw(amount)) { to.deposit(amount); System.out.println("Sent Rs. " + amount + " to " + to.getOwner()); } else { System.out.println("Failed: " + from.getOwner() + " cannot send Rs. " + amount); } }}
public class UpiDemo { public static void main(String[] args) { Account priya = new Account("Priya", 1000); Account arjun = new Account("Arjun", 200); UpiApp app = new UpiApp(); app.send(priya, arjun, 300); app.send(arjun, priya, 900); System.out.println("Priya: " + priya.getBalance() + ", Arjun: " + arjun.getBalance()); }}Sent Rs. 300 to Arjun Failed: Arjun cannot send Rs. 900 Priya: 700, Arjun: 500
What this code does
- The app only decides the order of steps. Each account checks and changes its own balance in
withdrawanddeposit. depositruns only ifwithdrawreturnedtrue, so a failed payment changes nothing: Arjun had only Rs. 500.
Each account guards its own balance; the app only decides the order of steps. A good sign: you tell an object what to do, from.withdraw(500), instead of reaching into its fields.
Next step
Check your understanding
11 quick questions