Skip to lesson

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

ShadowPartDemo.javaJava
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();    }}
Sample output
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 field engine stays null.
  • 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:

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

LeakArrayDemo.javaJava
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();    }}
Sample output
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, so main can write null into 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 variable i; an IDE shows the name.

Example 3 · The fix: return a copy

CopyArrayDemo.javaJava
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();    }}
Output
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 5

Choosing 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

AllLinksDemo.javaJava
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");    }}
Output
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 own Classroom. Aggregation: the teacher is made outside and only added to the department.
  • Association: guide uses the Student it is given and does not keep it. Delegation: messages go through the Notifier interface, 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