These are the notes for Low-Level Design (LLD) episode 10. We finished the four pillars of object-oriented programming (encapsulation, abstraction, inheritance, polymorphism). A real design is never one class, though: it is many objects that hold and use each other. We build a small college app, break it in five different ways, and invent the vocabulary every design interview uses: association (unidirectional and bidirectional), multiplicity, the has-a relationship with its two kinds, aggregation and composition, dependency, realization, coupling (tight vs loose), cohesion, and the object graph. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. The problem: a copied phone number
In our college app every student gets a mentor: a teacher who guides them. The obvious first design: the student writes down the mentor's name and phone number as text. A copy.
Two words we need first:
- A field is a variable that belongs to an object, declared inside the class.
String phone;insideTeacheris a field; everyTeacherobject has its ownphone. - A
Stringis Java's type for text, like"90000-11111".
class Teacher {
String name, phone;
Teacher(String name, String phone) { this.name = name; this.phone = phone; }
}
class Student {
String name, mentorName, mentorPhone;
Student(String name, String mentorName, String mentorPhone) {
this.name = name;
this.mentorName = mentorName;
this.mentorPhone = mentorPhone;
}
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao", "90000-11111");
Student ravi = new Student("Ravi", rao.name, rao.phone);
rao.phone = "90000-22222"; // she changes her number
System.out.println("Rao's phone: " + rao.phone);
System.out.println("Ravi calls: " + ravi.mentorPhone);
}
}
Rao's phone: 90000-22222
Ravi calls: 90000-11111
No error, just a wrong number. Ravi kept a copy of her data instead of a link to her. Copies don't hear about changes; we say the copy has gone stale (out of date).
2. Association: keep a reference, not a copy
A reference is the address of an object in memory. Think of a saved contact in your phone, not a number scribbled on paper: when the person updates their number, the contact still reaches them. In Java, a variable of a class type (like Teacher mentor) holds a reference, not a copy of the object.
class Teacher {
String name, phone;
Teacher(String name, String phone) { this.name = name; this.phone = phone; }
}
class Student {
String name;
Teacher mentor; // a reference, not a copy
Student(String name, Teacher mentor) {
this.name = name;
this.mentor = mentor;
}
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao", "90000-11111");
Student ravi = new Student("Ravi", rao);
rao.phone = "90000-22222"; // she changes her number
System.out.println("Rao's phone: " + rao.phone);
System.out.println("Ravi calls: " + ravi.mentor.phone);
}
}
Rao's phone: 90000-22222
Ravi calls: 90000-22222
Both lines show the new number. ravi.mentor.phone follows the link to the one and only Mrs Rao.
Association: one object keeps a reference to another in a field, so it can talk to it again and again. Student is associated with Teacher. It is a lasting link: it lives as long as the field holds it.
| In real life | In Java |
|---|---|
| A saved contact in your phone | A field holding a reference: Teacher mentor; |
| A number written on paper | A copied value: String mentorPhone; |
| The contact always reaches the person | The reference always sees the current object |
Unidirectional and bidirectional
- Unidirectional association (one-way): only one side knows the other. Here only
StudentknowsTeacher; aTeacherhas no idea who her mentees are. - Bidirectional association (two-way): both objects hold references to each other. Mrs Rao wants a list of her mentees, so now
Teachermust also knowStudent. This is harder, as the next two sections show.
3. Bidirectional association, trap 1: the sides disagree
A List is an ordered collection of objects; ArrayList is the common implementation (a list backed by a growable array). import java.util.*; brings in these collection classes. final on a field means it can be assigned only once.
import java.util.*;
class Teacher {
final String name;
final List<Student> mentees = new ArrayList<>();
Teacher(String name) { this.name = name; }
}
class Student {
final String name;
Teacher mentor;
Student(String name) { this.name = name; }
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao");
Student ravi = new Student("Ravi"), meena = new Student("Meena");
ravi.mentor = rao; rao.mentees.add(ravi);
meena.mentor = rao; // forgot the other side
System.out.println("Meena's mentor: " + meena.mentor.name);
System.out.println("Rao's mentees: " + rao.mentees.size());
}
}
Meena's mentor: Mrs Rao
Rao's mentees: 1
To link two objects both ways, you must set both sides. Meena's side was set, the list wasn't. Now the app tells two different stories.
Fix: never let callers set the two sides separately. One method, addMentee, does both in one place, and the list becomes private (visible only inside Teacher), so nobody can bypass it.
import java.util.*;
class Teacher {
final String name;
private final List<Student> mentees = new ArrayList<>();
Teacher(String name) { this.name = name; }
void addMentee(Student s) { // keeps BOTH sides in sync
mentees.add(s);
s.mentor = this;
}
List<String> menteeNames() { return mentees.stream().map(s -> s.name).toList(); }
}
class Student {
final String name;
Teacher mentor;
Student(String name) { this.name = name; }
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao");
Student ravi = new Student("Ravi"), meena = new Student("Meena");
rao.addMentee(ravi);
rao.addMentee(meena);
System.out.println("Meena's mentor: " + meena.mentor.name);
System.out.println("Rao's mentees: " + rao.menteeNames());
}
}
Meena's mentor: Mrs Rao
Rao's mentees: [Ravi, Meena]
this means "the current object" (here, the teacher whose addMentee was called). mentees.stream().map(s -> s.name).toList() turns the list of students into a list of their names: a stream processes the items one by one, map transforms each item, and s -> s.name is a lambda (episode 5), a tiny unnamed function ("given s, give back s.name").
4. Bidirectional association, trap 2: the endless loop
toString() is the method println calls to turn an object into text. Give both classes one: Teacher prints its name and its mentees, Student prints its name and its mentor.
import java.util.*;
class Teacher {
final String name;
final List<Student> mentees = new ArrayList<>();
Teacher(String name) { this.name = name; }
void addMentee(Student s) { mentees.add(s); s.mentor = this; }
public String toString() { return name + " mentors " + mentees; }
}
class Student {
final String name;
Teacher mentor;
Student(String name) { this.name = name; }
public String toString() { return name + " (mentor: " + mentor + ")"; }
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao");
rao.addMentee(new Student("Ravi"));
System.out.println(rao);
}
}
Exception in thread "main" java.lang.StackOverflowError
... (stack trace repeats)
Printing Rao prints her mentee list, which prints Ravi, which prints his mentor, Rao, which prints Ravi again, forever. Every method call is recorded on the call stack (the memory Java uses to track which methods are running and where to return). Endless calls fill it up, and Java throws StackOverflowError.
Rules for two-way links:
- Only one side may print, compare or copy the other (for example, Student prints only
mentor.name, see Practice 4). - Better still: prefer one-way associations, and add the second direction only when a real feature needs it.
5. Multiplicity: how many on each end?
Every association has a number on each end: how many objects can be on the other side. This is multiplicity.
| Multiplicity | Meaning | College example |
|---|---|---|
1 |
exactly one | a report card belongs to exactly 1 student |
0..1 |
zero or one | a new student has 0..1 mentor (maybe none yet) |
* |
any number, zero or more | a teacher has * mentees (many, or none) |
1..* |
at least one | a department has 1..* teachers |
Multiplicity isn't just a diagram label. 0..1 in the design means "can be null" in the code. null is Java's "no object here" value: a reference that points at nothing.
import java.util.*;
class Teacher {
final String name;
Teacher(String name) { this.name = name; }
}
class Student {
final String name;
Teacher mentor; // 0..1: may not be assigned yet
Student(String name, Teacher mentor) { this.name = name; this.mentor = mentor; }
String mentorName() { return mentor.name; }
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao");
List<Student> batch = List.of(new Student("Ravi", rao),
new Student("Arjun", null)); // joined today
for (Student s : batch)
System.out.println(s.name + " -> " + s.mentorName());
}
}
Ravi -> Mrs Rao
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "this.mentor" is null
at Student.mentorName(Main.java:10)
at Main.main(Main.java:18)
A NullPointerException (NPE) is thrown when code uses a null reference as if it pointed at an object. A 0..1 link was treated as exactly 1. (List.of(...) makes a fixed list from the given items.)
Fix: make the "zero" visible in the type. Optional<Teacher> (episode 5) is a box that either holds a Teacher or is empty, and the caller must say what to do when it's empty.
import java.util.*;
class Teacher {
final String name;
Teacher(String name) { this.name = name; }
}
class Student {
final String name;
Teacher mentor; // 0..1: may not be assigned yet
Student(String name, Teacher mentor) { this.name = name; this.mentor = mentor; }
Optional<Teacher> mentor() { return Optional.ofNullable(mentor); }
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao");
List<Student> batch = List.of(new Student("Ravi", rao),
new Student("Arjun", null)); // joined today
for (Student s : batch)
System.out.println(s.name + " -> " + s.mentor()
.map(t -> t.name).orElse("not assigned yet"));
}
}
Ravi -> Mrs Rao
Arjun -> not assigned yet
Optional.ofNullable(x) makes an empty box if x is null; .map(t -> t.name) changes a Teacher into her name if present; .orElse("...") gives the fallback when empty.
Rule of thumb: 0..1 becomes an Optional, * becomes a List (or another collection), 1 becomes a field that is always set (often final, set in the constructor).
6. Has-a relationships: aggregation and composition
Some associations are whole and part. A cricket team has players. A has-a relationship means one object contains another as a part: a field holding another object. Compare it with inheritance (episode 8), an is-a relationship: a car is a vehicle; a car has an engine.
There are two kinds of has-a:
| In real life | In Java | Name |
|---|---|---|
| A team is disbanded, players join another team | The part can outlive the whole, or be shared | Aggregation (weaker) |
| A house is demolished, its rooms are gone too | The whole creates and owns its parts; they live and die with it | Composition (stronger) |
Aggregation: a teacher outlives her department
import java.util.*;
class Teacher {
final String name;
Teacher(String name) { this.name = name; }
}
class Department {
final String name;
final List<Teacher> teachers = new ArrayList<>();
Department(String name) { this.name = name; }
void hire(Teacher t) { teachers.add(t); }
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao"); // exists on her own
Department physics = new Department("Physics");
physics.hire(rao);
physics = null; // the department closes
Department science = new Department("Science");
science.hire(rao); // same teacher moves
System.out.println(rao.name + " now teaches in " + science.name);
}
}
Mrs Rao now teaches in Science
Mrs Rao was created outside any department and handed in through hire. When we set physics = null, we drop our only reference to the Physics department (Java will later clean up an object nobody references). She lives on and joins Science. Aggregation: the department used her; it never owned her.
Composition: a report card owns its marks
A report card should own its marks. First attempt: the constructor just stores the list it is given.
import java.util.*;
class ReportCard {
private final List<Integer> marks;
ReportCard(List<Integer> marks) { this.marks = marks; }
int total() {
int t = 0;
for (int m : marks) t += m;
return t;
}
}
public class Main {
public static void main(String[] args) {
List<Integer> sheet = new ArrayList<>(List.of(80, 75, 90));
ReportCard ravi = new ReportCard(sheet);
sheet.clear(); // the clerk reuses the sheet
sheet.addAll(List.of(40, 35)); // for Meena
ReportCard meena = new ReportCard(sheet);
System.out.println("Ravi: " + ravi.total());
System.out.println("Meena: " + meena.total());
}
}
Ravi: 75
Meena: 75
Ravi's real total was 80 + 75 + 90 = 245. Both report cards point at the same list (sheet), so clearing and refilling it for Meena overwrote Ravi's marks. We wanted composition but built accidental sharing. (List<Integer> is a list of whole numbers; Integer is the object version of int.)
In composition, the whole creates its own parts and never shares them. So the report card makes its own new list from the values it receives (a defensive copy):
import java.util.*;
class ReportCard {
private final List<Integer> marks;
ReportCard(List<Integer> marks) { this.marks = new ArrayList<>(marks); }
int total() {
int t = 0;
for (int m : marks) t += m;
return t;
}
}
public class Main {
public static void main(String[] args) {
List<Integer> sheet = new ArrayList<>(List.of(80, 75, 90));
ReportCard ravi = new ReportCard(sheet);
sheet.clear(); // the clerk reuses the sheet
sheet.addAll(List.of(40, 35)); // for Meena
ReportCard meena = new ReportCard(sheet);
System.out.println("Ravi: " + ravi.total());
System.out.println("Meena: " + meena.total());
}
}
Ravi: 245
Meena: 75
Each card owns its marks, and they go away with the card.
| Aggregation | Composition | |
|---|---|---|
| Who creates the part? | Someone outside, then passes it in | The whole itself (or copies what it's given) |
| Can the part be shared? | Yes | No |
| Part's lifetime | Independent of the whole | Ends with the whole |
| Example | Department and Teacher | ReportCard and its marks, House and Room |
| UML symbol | hollow diamond on the whole's end | filled diamond on the whole's end |
7. Dependency and realization
| In real life | In Java | Name |
|---|---|---|
| Your own scooter, parked at home, always yours | A reference kept in a field | Association (lasting) |
| An auto rickshaw for one trip: use it, pay, walk away | A class used only as a parameter or local variable inside one method, never stored | Dependency ("uses-a", the weakest link) |
| A "UPI accepted" sticker: the shop promises to take UPI | A class implements an interface |
Realization (fulfils a contract) |
A parameter is a variable a method receives when called (n in remind(String phone, Notifier n)); a local variable is declared inside a method and disappears when it returns. An interface (episode 3) is a contract: a list of methods a class promises to provide.
interface Notifier {
void send(String to, String msg);
}
class SmsNotifier implements Notifier {
public void send(String to, String msg) { System.out.println("SMS to " + to + ": " + msg); }
}
class WhatsAppNotifier implements Notifier {
public void send(String to, String msg) { System.out.println("WhatsApp to " + to + ": " + msg); }
}
class FeeDesk {
// dependency: uses a Notifier for one call, never stores it
void remind(String phone, Notifier n) {
n.send(phone, "Fee due: Rs 5000");
}
}
public class Main {
public static void main(String[] args) {
FeeDesk desk = new FeeDesk();
desk.remind("90000-33333", new SmsNotifier());
desk.remind("90000-44444", new WhatsAppNotifier());
}
}
SMS to 90000-33333: Fee due: Rs 5000
WhatsApp to 90000-44444: Fee due: Rs 5000
SmsNotifierandWhatsAppNotifierimplementNotifier: that's realization, twice.FeeDesk.remindtakes aNotifier, uses it once, and forgets it. No field: that's a dependency.FeeDesknever changed between the two channels. It depends only on the interface, so any notifier plugs in.
On a class diagram (UML): a dependency is a dashed line with an open arrowhead pointing at the class that is used. Realization is a dashed line with a hollow triangle pointing at the interface. Inheritance (from the last episodes) uses the same hollow triangle but with a solid line. UML (Unified Modeling Language) is the standard set of drawing rules for software diagrams; a class diagram shows classes as boxes and their relationships as lines.
8. Coupling: tight vs loose
| Phones | Classes |
|---|---|
| A charger soldered onto the phone: replace the charger, open up the phone | Tight coupling: one class knows another's insides, so a change in one forces changes in the other |
| A standard USB-C port: any charger fits, the phone's insides can change freely | Loose coupling: classes talk through a small, stable set of methods or an interface |
| How much one knows about the other | Coupling: the degree to which one class depends on, and knows about, another. Less is better |
Student's marks used to be a public List<Integer>, and a RankList class, written by someone else, reached straight into it with size() and get(i). Today Student's author switches marks to a plain int[] array (a fixed-size row of numbers), touching only Student. (int... marks is varargs: the constructor accepts any number of int arguments and receives them as an array.)
class Student {
final String name;
final int[] marks; // was: List<Integer> marks
Student(String name, int... marks) { this.name = name; this.marks = marks; }
}
class RankList { // nobody touched this class
static int total(Student s) {
int t = 0;
for (int i = 0; i < s.marks.size(); i++) t += s.marks.get(i);
return t;
}
}
public class Main {
public static void main(String[] args) {
Student ravi = new Student("Ravi", 80, 75, 90);
System.out.println(ravi.name + ": " + RankList.total(ravi));
}
}
Main.java:9: error: cannot find symbol
for (int i = 0; i < s.marks.size(); i++) t += s.marks.get(i);
^
symbol: method size()
location: variable marks of type int[]
Main.java:9: error: cannot find symbol
for (int i = 0; i < s.marks.size(); i++) t += s.marks.get(i);
^
symbol: method get(int)
location: variable marks of type int[]
2 errors
"Cannot find symbol" is the compiler saying "that name doesn't exist here": an array has no size() or get() methods. The errors are in RankList, a class nobody touched. RankList depended on Student's insides, so a private decision became everyone's problem: tight coupling.
Loosen it: make marks private and offer a method. RankList asks the student for its total instead of digging through its fields.
class Student {
final String name;
private final int[] marks; // hidden: free to change
Student(String name, int... marks) { this.name = name; this.marks = marks; }
int total() {
int t = 0;
for (int m : marks) t += m;
return t;
}
}
class RankList {
static int total(Student s) { return s.total(); } // asks, doesn't dig
}
public class Main {
public static void main(String[] args) {
Student ravi = new Student("Ravi", 80, 75, 90);
System.out.println(ravi.name + ": " + RankList.total(ravi));
}
}
Ravi: 245
Student can switch back to a list tomorrow and RankList never notices. Loose coupling: depend on a few stable methods or an interface, never on another class's fields or concrete details. (This is encapsulation from episode 6 paying off.)
9. Cohesion
Coupling is about the links between classes. Its partner, cohesion, is about what's inside one class: how strongly the parts of a class belong together.
A junk drawer holds batteries, keys, spoons and rubber bands: finding anything is slow, and every family member opens it. A cutlery drawer holds only cutlery.
// low cohesion: unrelated jobs in one class
class CollegeHelper {
int calculateFee(Student s)
void sendSms(String to)
byte[] makePdf(ReportCard r)
void markAttendance(Student s)
}
// high cohesion: one focused job each
class FeeCalculator { int fee(Student s) }
class SmsNotifier { void send(...) }
class ReportPdf { byte[] render(...) }
class Attendance { void mark(Student s) }
(These are outlines, not compilable code; byte[] is an array of raw bytes, the usual type for a file's contents like a PDF.)
The goal of every design review: high cohesion inside each class, loose coupling between classes.
| Problem | Symptom |
|---|---|
| Low cohesion | One class changes for many unrelated reasons |
| Tight coupling | One change breaks many classes |
Both make a code base scary to touch. The SOLID episodes (starting in episode 12) make this precise.
10. The object graph
At run time, all these objects and the references between them form a network called the object graph. Each object is a node (a dot); each reference is an edge (an arrow from the object that holds the reference to the object it points at).
college --> physics --> Mrs Rao <==> Ravi --> report card
Printing, copying or saving an object means walking this graph: following every reference. That's exactly why the two-way toString loop in section 4 overflowed: the walk went Rao to Ravi to Rao forever, because the graph had a cycle (a path that comes back to where it started).
The class diagram
Today's design as a class diagram (UML). Fields start with - (private), methods with + (public).
College ◆-----------------> Department ◇-----------------> Teacher
- name: String 1 1..* - name: String * 1..* - name: String
+ hire(t: Teacher) + addMentee(s: Student)
| 0..1 mentor
| (association, both ways: "mentors")
| * mentees
ReportCard <-----------------------------------------◆ Student
- marks: List<Integer> 1 1 - name: String
+ total(): int + mentor(): Optional<Teacher>
| Link | Kind | Symbol | Multiplicity | Why |
|---|---|---|---|---|
| College to Department | Composition | filled diamond on College | 1 to 1..* | Close the college and its departments go too |
| Department to Teacher | Aggregation | hollow diamond on Department | * to 1..* | Teachers can move, and may work in several departments |
| Teacher and Student | Bidirectional association | plain line | 0..1 mentor, * mentees | Each knows the other; a new student may have no mentor yet |
| Student to ReportCard | Composition | filled diamond on Student | 1 to 1 | Each student owns exactly one report card |
| FeeDesk to Notifier | Dependency | dashed line, open arrow | (none) | Used as a parameter only |
| SmsNotifier, WhatsAppNotifier to Notifier | Realization | dashed line, hollow triangle | (none) | They implement the interface |
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
String mentorPhone = rao.phone; |
no error: Ravi calls: 90000-11111 |
Copied data goes stale | Keep a reference: Teacher mentor |
meena.mentor = rao; (list not updated) |
no error: Rao's mentees: 1 |
Two-way link set on one side | One method (addMentee) sets both sides |
toString() on both sides of a two-way link |
Exception in thread "main" java.lang.StackOverflowError |
Endless loop through the object graph | Only one side prints the other |
return mentor.name; when mentor is 0..1 |
java.lang.NullPointerException: Cannot read field "name" because "this.mentor" is null |
0..1 treated as 1 |
Return Optional<Teacher> |
| Storing a list you were given, for composition | no error: Ravi: 75 |
The part is shared, not owned | this.marks = new ArrayList<>(marks); |
s.marks.get(i) from another class |
error: cannot find symbol / symbol: method get(int) |
Tight coupling to a field | Private field + a method (total()) |
Mini project
Model a library (the video's homework): Library, Book, Member, Loan. Requirements:
- The library creates its books (composition); members exist on their own and join (aggregation).
- A member has
0..*loans; each loan has exactly1member and1book. Member and Loan are linked both ways, and one method keeps both sides in sync. - A loan's return date is
0..1: expose it as anOptional. - Print a summary, what Ravi borrowed, and each loan's return status.
Solution
import java.util.*;
class Book {
final String title;
Book(String title) { this.title = title; }
}
class Loan {
final Member member; // exactly 1
final Book book; // exactly 1
private String returnedOn; // 0..1: null until returned
Loan(Member member, Book book) { this.member = member; this.book = book; }
void giveBack(String date) { returnedOn = date; }
Optional<String> returnedOn() { return Optional.ofNullable(returnedOn); }
}
class Member {
final String name;
private final List<Loan> loans = new ArrayList<>(); // 0..* loans
Member(String name) { this.name = name; }
Loan borrow(Book b) { // the ONLY way to make a loan: both sides in sync
Loan loan = new Loan(this, b);
loans.add(loan);
return loan;
}
List<String> borrowed() { return loans.stream().map(l -> l.book.title).toList(); }
}
class Library {
private final List<Book> books = new ArrayList<>(); // composition: the library creates its books
private final List<Member> members = new ArrayList<>(); // aggregation: members exist on their own
Book addBook(String title) {
Book b = new Book(title);
books.add(b);
return b;
}
void join(Member m) { members.add(m); }
String summary() { return books.size() + " books, " + members.size() + " members"; }
}
public class Main {
public static void main(String[] args) {
Library lib = new Library();
Book java = lib.addBook("Java Basics");
Book dsa = lib.addBook("DSA Notes");
Member ravi = new Member("Ravi");
lib.join(ravi);
Loan first = ravi.borrow(java);
Loan second = ravi.borrow(dsa);
first.giveBack("2026-07-01");
System.out.println(lib.summary());
System.out.println(ravi.name + " borrowed " + ravi.borrowed());
System.out.println(first.book.title + " returned: " + first.returnedOn().orElse("not yet"));
System.out.println(second.book.title + " returned: " + second.returnedOn().orElse("not yet"));
System.out.println("Loan points back to: " + second.member.name);
}
}
Output:
2 books, 1 members
Ravi borrowed [Java Basics, DSA Notes]
Java Basics returned: 2026-07-01
DSA Notes returned: not yet
Loan points back to: Ravi
The Loan constructor receives this (the member), and borrow adds the loan to the member's list in the same method, so the two sides can never disagree. No toString prints the other side, so there is no loop.
Practice
- What does this print? Is
Bagaggregation or composition? Make it composition.
import java.util.*;
class Bag {
private final List<String> items;
Bag(List<String> items) { this.items = items; }
int size() { return items.size(); }
}
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("pen"));
Bag bag = new Bag(list);
list.add("book");
System.out.println(bag.size());
}
}
Solution
It prints 2. The bag shares the caller's list, so the caller's later add shows up inside the bag: that's aggregation (or accidental sharing). For composition, copy in the constructor: this.items = new ArrayList<>(items);. With that one change the program prints 1.
- Name the relationship: (a)
class Car { private final Engine engine = new Engine(); }(b)class Playlist { void add(Song s) { songs.add(s); } }, where the same songs appear in many playlists (c)class Printer { void print(Document d) { ... } }(d)class Circle implements Shape(e) aDoctorholds a list ofPatients and eachPatientholds itsDoctor.
Solution
(a) Composition: Car creates and owns its engine. (b) Aggregation: songs exist independently and are shared. (c) Dependency: Document is only a parameter. (d) Realization. (e) Bidirectional association (keep both sides in sync with one method).
- Write the multiplicity for each end: an
Orderand itsOrderLines (an order needs at least one line); aPersonand aPassport; aCourseand theStudents enrolled. Which of these should be anOptionalin code?
Solution
Order 1 to OrderLine 1..*; Person 1 to Passport 0..1; Course * to Student * (a course can have any number of students, a student any number of courses). The passport (0..1) should be returned as Optional<Passport>.
- Fix the
StackOverflowErrorin section 4 while keeping bothtoStringmethods. What's the output?
Solution
Let only one side print the other in full. Student prints just the mentor's name:
import java.util.*;
class Teacher {
final String name;
final List<Student> mentees = new ArrayList<>();
Teacher(String name) { this.name = name; }
void addMentee(Student s) { mentees.add(s); s.mentor = this; }
public String toString() { return name + " mentors " + mentees; }
}
class Student {
final String name;
Teacher mentor;
Student(String name) { this.name = name; }
public String toString() { // prints only the mentor's NAME, not the whole mentor
return name + " (mentor: " + (mentor == null ? "none" : mentor.name) + ")";
}
}
public class Main {
public static void main(String[] args) {
Teacher rao = new Teacher("Mrs Rao");
rao.addMentee(new Student("Ravi"));
System.out.println(rao);
}
}
Mrs Rao mentors [Ravi (mentor: Mrs Rao)]
cond ? a : b (the ternary operator) gives a if the condition is true, else b.
ShippingServicecomputes delivery charges withorder.customer.address.city.equals("Pune"). What kind of coupling is this, and how would you loosen it?
Solution
Tight coupling: ShippingService knows the inner fields of Order, Customer and Address, so changing any of them breaks it. Loosen it by asking instead of digging: give Order a method such as String deliveryCity() and call order.deliveryCity(). Only Order then needs to know how the city is found.
Quick quiz
class Order {
private final List<OrderLine> lines = new ArrayList<>();
void add(String item, int qty) {
lines.add(new OrderLine(item, qty));
}
}
Which relationship is Order to OrderLine?
- Dependency
- Aggregation
- Composition
- Realization
Answer
Composition. Order creates its OrderLines itself inside add and never shares them: they live and die with the order. If the order received existing objects that others also use, it would be aggregation.
Interview questions
- What is association? A relationship where one object holds a reference to another in a field and uses it over time. Example:
StudenthasTeacher mentor. - Unidirectional vs bidirectional association? One-way: only one side knows the other. Two-way: both hold references; you must keep both sides in sync (one method sets both) and avoid infinite loops in
toString,equalsor copying. Prefer one-way. - Aggregation vs composition? Both are has-a. Aggregation: parts exist independently and can be shared (Department and Teacher, hollow diamond). Composition: the whole creates and owns its parts, which die with it (House and Room, filled diamond).
- How do you implement composition in Java? Create the parts inside the whole (or defensively copy what's passed in), keep them
private, and never hand out references that let others change them. - What is a dependency? The weakest relationship: a class uses another only temporarily, as a method parameter, local variable or return type, without storing it. Dashed arrow in UML.
- What is realization? A class implementing an interface, fulfilling its contract. Dashed line with a hollow triangle.
- What is multiplicity, and how does it map to code? How many objects can be at each end of an association:
1is a required field,0..1anOptional(or nullable),*and1..*a collection. - What are coupling and cohesion, and what's the goal? Coupling: how much classes depend on each other. Cohesion: how strongly one class's parts belong together. Aim for loose coupling and high cohesion.
- How do you reduce coupling? Hide fields (
private), expose a few stable methods, depend on interfaces instead of concrete classes, and pass dependencies in rather than reaching through chains of fields. - What is an object graph? The network of objects (nodes) and references (edges) at run time. Serialization, deep copying and printing walk it, so cycles need care.
Glossary
| Term | Meaning, with an example |
|---|---|
| Field | A variable that belongs to an object. String phone; in Teacher |
String |
Java's text type. "90000-11111" |
| Stale copy | A copied value that no longer matches the original. Ravi's old phone number |
| Reference | The address of an object; like a saved contact. Teacher mentor |
| Association | One object keeps a reference to another in a field and uses it over time. Student and mentor |
| Unidirectional association | Only one side knows the other. Student knows Teacher |
| Bidirectional association | Both objects hold references to each other. Teacher's mentees + Student's mentor |
List / ArrayList |
An ordered collection / its usual growable-array implementation |
private |
Visible only inside the class. private final List<Student> mentees |
final field |
Can be assigned only once |
this |
The current object |
Stream, map, toList() |
Process items one by one, transform each, collect into a list |
| Lambda | A tiny unnamed function. s -> s.name |
toString() |
The method println calls to turn an object into text |
| Call stack | Memory Java uses to track running method calls |
StackOverflowError |
Thrown when calls go too deep, e.g. endless recursion |
| Multiplicity | How many objects can be at each end of an association. 1, 0..1, *, 1..* |
null |
"No object here": a reference pointing at nothing |
NullPointerException |
Thrown when a null reference is used as an object |
Optional |
A box that holds a value or is empty. Optional<Teacher> |
| Has-a relationship | One object contains another as a part. A car has an engine |
| Is-a relationship | Inheritance. A car is a vehicle |
| Aggregation | Has-a where parts live independently and can be shared. Department and Teacher |
| Composition | Has-a where the whole creates and owns its parts; they die with it. ReportCard and marks |
| Accidental sharing | Two objects unintentionally pointing at the same mutable object. Two report cards, one sheet |
| Defensive copy | Copying data you receive so nobody else can change it. new ArrayList<>(marks) |
| Parameter | A variable a method receives when called |
| Local variable | A variable declared inside a method; gone when it returns |
| Interface | A contract: methods a class promises to provide. Notifier |
| Dependency | Using another class briefly (parameter or local variable), not storing it. FeeDesk uses Notifier |
| Realization | A class implementing an interface. SmsNotifier implements Notifier |
| UML | Unified Modeling Language, standard drawing rules for software diagrams |
| Class diagram | A UML picture of classes (boxes) and relationships (lines) |
Array (int[]) |
A fixed-size row of values |
Varargs (int...) |
A parameter accepting any number of arguments, received as an array |
cannot find symbol |
Compiler error: the name doesn't exist on that type |
| Coupling | How much one class depends on and knows about another |
| Tight coupling | Classes entangled so a change in one forces changes in others. RankList using s.marks.get(i) |
| Loose coupling | Classes talk through a few stable methods or interfaces. s.total() |
| Cohesion | How strongly the parts of one class belong together |
| High / low cohesion | One focused job (FeeCalculator) / unrelated jobs mixed (CollegeHelper) |
| Object graph | Objects (nodes) and references (edges) at run time |
| Node / edge | A dot in a graph (an object) / a link between dots (a reference) |
| Cycle | A path in a graph that returns to its start. Rao to Ravi to Rao |
Summary
- Association: keep a reference in a field, not a copy; copies go stale.
- Unidirectional links are simple; bidirectional links need one method that sets both sides, and only one side may print the other (or
StackOverflowError). - Multiplicity (
1,0..1,*,1..*) drives the code:0..1meansOptional,*means a collection. - Has-a: aggregation shares independent parts; composition creates and owns its parts (defensive copy).
- Dependency is brief use (parameter); realization is implementing an interface.
- Coupling: depend on methods and interfaces, never on another class's fields. Cohesion: one focused job per class.
- The object graph is what printing, copying and saving walk.
Next episode: Composition over inheritance: delegation, behaviour injection and the class explosion problem.