Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Every relationship in this module answers two questions: how does one object reach another, and who controls its life? Most bugs come from a wrong answer, or from a forgotten this., copy or count.
Mistakes and fixes at a glance
The most common relationship bug is a part that was never stored. engine = engine; in the constructor sets the parameter, not the field, so the bike is built without an engine and crashes later.
Example 1 · A part lost to shadowing
class Engine { private int cc;
Engine(int cc) { this.cc = cc; }
int getCc() { return cc; }}
class Bike { private String model; private Engine engine;
Bike(String model, Engine engine) { this.model = model; engine = engine; }
void start() { System.out.println(model + " starts with a " + engine.getCc() + " cc engine"); }}
public class ShadowPartDemo { public static void main(String[] args) { Bike bike = new Bike("Pulsar", new Engine(150)); System.out.println("Bike created"); bike.start(); }}Bike created Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Engine.getCc()" because "this.engine" is null at Bike.start(ShadowPartDemo.java:19) at ShadowPartDemo.main(ShadowPartDemo.java:27)
What this code does
engine = engine;sets the parameter to itself, because the parameter shadows the field. The fieldenginestaysnull.- The object is built without any error; the crash comes later, in
start(). Fix:this.engine = engine;.
Review: Objects inside objects (opens in a new tab). The other common mistakes, each with the fix:
extendsonly to reuse code (Stack extends NumberList) → a private field plus forwarding. Review: HAS-A vs IS-A (opens in a new tab)- NPE in a loop over an array of parts → loop to
count; checkcount < array.lengthbefore adding. Review: Association (opens in a new tab) - One side of a two-way link set, or both sides calling each other → one method sets both sides. Review: Association (opens in a new tab)
- A whole that calls
newfor parts that should be shared → take ready objects; after a remove, clear the slot andcount--. Review: Aggregation (opens in a new tab) - A getter that returns an owned part or array → return a copy or only the data. Review: Composition (opens in a new tab)
- A missing delegate, or a subclass per behaviour → require the delegate in the constructor; use an interface and a setter. Review: Delegation (opens in a new tab)
Mistakes that compile but corrupt data
A getter that returns the team's own array lets main write null into it. Nothing fails at that line; the crash comes later, inside the team's own method.
Example 2 · A leaking array crashes the team
class Player { private String name;
Player(String name) { this.name = name; }
String getName() { return name; }}
class Team { private Player[] players = new Player[3]; private int count;
void add(Player p) { players[count] = p; count++; }
Player[] getPlayers() { return players; }
void show() { for (int i = 0; i < count; i++) { System.out.println(players[i].getName()); } }}
public class LeakArrayDemo { public static void main(String[] args) { Team t = new Team(); t.add(new Player("Smriti")); t.add(new Player("Harmanpreet")); Player[] list = t.getPlayers(); list[0] = null; t.show(); }}Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Player.getName()" because "this.players[<local1>]" is null at Team.show(LeakArrayDemo.java:22) at LeakArrayDemo.main(LeakArrayDemo.java:34)
What this code does
getPlayers()returns the team's own array, somaincan writenullinto it. The team still thinks it has 2 players.- The crash happens later, inside
show(), far from the real mistake. That is why leaks are hard to debug. - Compiled with plain
javac, the message shows<local1>for the loop variablei; an IDE shows the name.
Example 3 · The fix: return a copy
import java.util.Arrays;
class Player { private String name;
Player(String name) { this.name = name; }
String getName() { return name; }}
class Team { private Player[] players = new Player[3]; private int count;
void add(Player p) { if (count < players.length) { players[count] = p; count++; } }
Player[] getPlayers() { return Arrays.copyOf(players, count); }
void show() { for (int i = 0; i < count; i++) { System.out.println(players[i].getName()); } }}
public class CopyArrayDemo { public static void main(String[] args) { Team t = new Team(); t.add(new Player("Smriti")); t.add(new Player("Harmanpreet")); Player[] list = t.getPlayers(); list[0] = null; System.out.println("Copy length: " + list.length); t.show(); }}Copy length: 2 Smriti Harmanpreet
What this code does
Arrays.copyOf(players, count)returns a new array with just the filled places. Changing it cannot touch the team's array.- The players inside are still the same objects, which is right here: players live on their own (aggregation).
The same leak happens with an object part, like an employee's ID card, and has the same fix. Two more silent bugs: a child class that counts twice because of the parent's inner calls (Review: Composition vs inheritance (opens in a new tab)), and a two-way link set on one side only, where the data is simply wrong.
Spot the bug
Each snippet looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask: who creates the part, who else holds it, and is every side of every link set?
Find the bug
Find the relationship bug
Select the line that is wrong.
main wants the shop owner to greet customers.
Round 1 of 5Choosing the right link
To choose, start at the strongest link and move down; stop at the first one that is true. One program can use them all: the department below composes, aggregates, associates and delegates.
Example 4 · Every relationship in one program
interface Notifier { void send(String msg);}
class Person { private String name;
Person(String name) { this.name = name; }
String getName() { return name; }}
class Student { private String name;
Student(String name) { this.name = name; }
String getName() { return name; }}
class Teacher extends Person { Teacher(String name) { super(name); }
void guide(Student s) { System.out.println(getName() + " guides " + s.getName() + " on a project"); }}
class Classroom { private String code;
Classroom(String code) { this.code = code; }
String getCode() { return code; }}
class Department { private String name; private Classroom room; private Teacher[] teachers = new Teacher[5]; private int count; private Notifier notifier;
Department(String name, String roomCode, Notifier notifier) { this.name = name; this.room = new Classroom(roomCode); this.notifier = notifier; }
void addTeacher(Teacher t) { if (count == teachers.length) { return; } teachers[count] = t; count++; notifier.send(t.getName() + " joined " + name + " (room " + room.getCode() + ")"); }}
public class AllLinksDemo { public static void main(String[] args) { Teacher meena = new Teacher("Meena"); Department cse = new Department("CSE", "B-204", msg -> System.out.println("SMS: " + msg)); cse.addTeacher(meena); meena.guide(new Student("Rahul")); System.out.println(meena.getName() + " is a Person and lives on her own"); }}SMS: Meena joined CSE (room B-204) Meena guides Rahul on a project Meena is a Person and lives on her own
What this code does
- IS-A:
Teacher extends Person. Composition: the department creates its ownClassroom. Aggregation: the teacher is made outside and only added to the department. - Association:
guideuses theStudentit is given and does not keep it. Delegation: messages go through theNotifierinterface, here a lambda.
- Composition: the whole creates and owns its parts (House–Room).
- Aggregation: the whole groups parts made outside (Department–Teacher).
- Association: one object just uses another (Teacher guides Student).
- Delegation: the whole forwards work, often through an interface (Department–Notifier). IS-A sits apart: only when the sentence test and the "keeps every promise" check both pass.
Finish up
Mark complete & continue
Next: Must-do problems: Composition and Relationships