CSSE2002 — Week 3 Notes

Object Oriented Programming II

See csse2002 for course logistics. Continues 2026-03-05-object-oriented-programming-i.

The week has two parts:

  1. Object Oriented Programming II: interface vs abstract class, encapsulation revision, mutability, polymorphism, casting.
  2. Specification: Javadoc, restrictiveness, generality, clarity, formality, contracts, defensive programming.

Three items are homework (self-study): primitive casting, defensive copying, and how a subclass can introduce mutability.

Recap: the four (five) pillars

Week 2 covered objects/classes/OOP, encapsulation, inheritance and abstraction. This week adds polymorphism as the fifth, and goes back over encapsulation and the interface/abstract-class comparison in more depth.

Interface vs abstract class

Week 2 left this comparison as homework. The full treatment is in java-abstraction. In short:

  • An interface defines a capability or contract — Flyable, Runnable, Payable. Unrelated classes can share it: Bird implements Flyable and Plane implements Flyable.
  • An abstract class defines a shared base implementation — common behaviour that subclasses inherit rather than restate.

In code, the interface carries nothing but a signature. The abstract class carries a finished method alongside an unfinished one.

public interface PaymentProcessor {
    void processPayment(double amount);
}
public abstract class Payment {
    public void validateTransaction() {
        System.out.println("Validating transaction...");
    }

    abstract void processPayment(double amount);
}

The course’s running Animal example has the same shape. eat() is inherited as-is, and makeSound() must be supplied by each subclass:

abstract class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }

    public abstract void makeSound();
}

class Dog extends Animal {
    @Override
    public void makeSound() { System.out.println("Dog barks"); }
}

class Cat extends Animal {
    @Override
    public void makeSound() { System.out.println("Cat Meows"); }
}

Figure 1: The abstract-class case: shared behaviour (eat()) lives in Animal, while each subclass supplies its own makeSound(). One connector joins both subclasses to the parent, with a single arrowhead into Animal.

The two combine. A class has at most one superclass, as many interfaces as you like.

class Dog  extends Animal implements Runnable, Swimmable
class Duck extends Animal implements Flyable,  Swimmable

Revising encapsulation

Person from java-encapsulation again: private fields with public getters. One field matters for the next section:

public class Person {
    private String name;
    private int age;
    private String email;
    private String[] phoneNumber;   // <- a mutable field

    public Person(String name, int age, String email, String[] phoneNumber) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

    public String getName()          { return name; }
    public int getAge()              { return age; }
    public String getEmail()         { return email; }
    public String[] getPhoneNumber() { return phoneNumber; }
}

The array field is the case where private and final together are still not enough.

Mutable vs immutable classes

See java-mutability — mutable and immutable class design, the arrays/lists gotcha where final protects only the reference, and defensive copying.

Polymorphism

See java-polymorphism — compile-time (overloading), runtime (overriding / dynamic method dispatch), and subtype polymorphism.

Casting

See java-casting — primitive widening/narrowing, and reference upcasting/downcasting. Practised in week4-tutorial-method-dispatch-and-casting.

Worked: what is the parent of Student?

What is the parent of class Student?

public class Student {
    public void study() {
        System.out.println("CSSE2002");
    }
}

Object. A class with no extends clause still has a superclass. The class hierarchy has Object at the root of everything.

Specification

See java-specification — Javadoc, restrictiveness, generality, clarity, formality, contracts, and defensive programming.

Key takeaways

Object oriented programming:

  • Encapsulation protects implementation details and prevents direct access to internal state.
  • Inheritance lets a class reuse behaviour from another class — but can expose the internal implementation details of a superclass.
  • Abstraction hides complex implementation detail: the user knows what it does, not how it works internally.
  • Polymorphism lets objects be treated as their common type, and lets different objects respond differently to the same method call.

OOP helps build flexible, reusable, and maintainable software by organizing code around objects and behaviour.

Specification:

  • A specification describes the contract between a method and its client.
  • It explains what the method does, not how it is implemented.
  • A good specification clearly states preconditions (true before the call), postconditions (true after a successful call) and side effects (any other change the method makes to the system).
  • Clear specifications make code easier to understand, use and maintain.

Java Classes - Point Line Polynomial

Practical exercises for week 3, building up a small set of geometry classes (Point, then Line on top of it, then an independent Polynomial) to practice java-encapsulation and java-mutability (note that movePoint/flipPoint/scale-style methods return a new object rather than mutating this).

The sheet opens with a habit it then assumes for the rest of semester:

Note on testing. From now on, whenever we ask you to write a class, you should also write a simple main method to test its functionality. This does not need to be in the same class (not every class needs a main method — testing class Foo and class Bar in class Test is fine).

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "5.0"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).

Figure 2: The worked plane the first three questions build against, combining three separate plots from the week 3 practical solutions: the two points (2,3) and (4,1) of p1, the line joining them of p2, and the midpoint of p7 labelled with the formula the sheet prints. The midpoint of this particular line is (3,2).

Question 1 — Points

Write a Point class representing an x,y-coordinate on a Cartesian plane. A Point stores two floats, one for each coordinate, with:

  • Point(float x, float y) and a default Point() (both 0).
  • float getX()/float getY().
  • Point movePoint(float deltaX, float deltaY) — returns a new Point at (getX() + deltaX, getY() + deltaY). The sheet emphasises: this method should not modify the Point it is called on.
  • static double distance(Point p, Point q) — Euclidean distance between \(p = (x_1, y_1)\) and \(q = (x_2, y_2)\):

\[d\big((x_1,y_1),(x_2,y_2)\big) = \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}\]

If p1 = new Point() and p2 = p1.movePoint(4, 5), what does p2 print (assuming a toString of "(" + x + ", " + y + ")")?

public class Point {
    private float x;
    private float y;

    public Point() {
        this(0, 0);
    }

    public Point(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float getX() { return this.x; }
    public float getY() { return this.y; }

    public Point movePoint(float deltaX, float deltaY) {
        return new Point(this.x + deltaX, this.y + deltaY);
    }

    public static double distance(Point p, Point q) {
        double x = p.x - q.x;
        double y = p.y - q.y;
        return Math.sqrt(x * x + y * y);
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

Three details in the model answer worth copying:

  • The default constructor is written this(0, 0) — constructor chaining — rather than repeating the two assignments. One place initialises the fields.
  • movePoint deliberately returns a new Point rather than mutating this, so p1 is left at (0.0, 0.0) and p2 is (4.0, 5.0).
  • distance is static and reads p.x and q.x directly, not through getX(). That compiles because private in Java is per-class, not per-object: any Point method can reach any other Point’s private fields.

Question 2 — Lines

Write a Line class storing a start Point, an end Point, and the (precomputed) double length between them, with:

  • Line(Point start, Point end) — also stores the distance between the two points — and a default Line() (both ends at the origin, length 0).
  • getStart()/getEnd()/getLength().
  • void moveStart(float deltaX, float deltaY) / void moveEnd(float deltaX, float deltaY) — mutator methods that move the line’s start/end by the given values.

For a Line from (0, 0) to (3, 4), what is getLength()?

public class Line {
    private Point start;
    private Point end;
    private double length;

    public Line() {
        this.start = new Point();
        this.end = new Point();
        this.length = 0;
    }

    public Line(Point start, Point end) {
        this.start = start;
        this.end = end;
        this.length = Point.distance(start, end);
    }

    public Point getStart() { return start; }
    public Point getEnd() { return end; }
    public double getLength() { return length; }

    public void moveStart(float deltaX, float deltaY) {
        start = start.movePoint(deltaX, deltaY);
        length = Point.distance(start, end);
    }

    public void moveEnd(float deltaX, float deltaY) {
        end = end.movePoint(deltaX, deltaY);
        length = Point.distance(start, end);
    }

    @Override
    public String toString() {
        return start.toString() + " " + end.toString() + " " + this.getLength();
    }
}

(0,0) to (3,4) is a 3-4-5 right triangle, so the length is exactly 5.0.

Note the two designs sitting side by side, deliberately: Point.movePoint is immutable (returns a new object, void nowhere in sight) while Line.moveStart/moveEnd are mutators (void, changing this). moveStart is written on top of the immutable one — start = start.movePoint(...) builds a fresh Point and rebinds the field to it, rather than reaching into the old Point and editing it.

length is a derived field: it is not independent state, it is a cached function of start and end. That is why every method that touches an endpoint has to recompute it on the next line. Storing it at all is a choice the sheet makes for you (the question says a Line stores “a double representing the length”), and the recomputation is the price — see java-encapsulation on keeping an object’s fields consistent with each other.

Question 3 — Testing and toString

Unless overridden, printing an object prints its class name and memory location, e.g. Point@30f39991 — the class name Point plus the location in memory 30f39991. Writing a toString() that returns a String overrides that default when a class instance is converted to a string, and makes testing by eye possible at all.

The sheet’s own reason for doing this now rather than later: “Now is a good opportunity to test your program, if you haven’t already. It is a bad idea to write too much code before checking that it works.”

Point p1 = new Point();
Point p2 = p1.movePoint(4, 5);

System.out.println(p1); // (0.0, 0.0)
System.out.println(p2); // (4.0, 5.0)

Line’s version delegates to Point’s rather than reaching for start.getX() and friends:

@Override
public String toString() {
    return start.toString() + " " + end.toString() + " " + this.getLength();
}

Question 4 — Additional methods

Add to Point:

  • Line createLine(Point end) — a Line with this as the start and end as the end.
  • Point flipPoint() — returns a new object with the sign of both coordinates changed, e.g. \((-1, 2)\) becomes \((1, -2)\).

Add to Line:

  • Point middle() — the midpoint of the start and end, at \(\left(\frac{x_1+x_2}{2}, \frac{y_1+y_2}{2}\right)\).
  • Line flipLine() — a new Line with both endpoints flipped as above.

What does new Point(-1, 2).flipPoint() print?

Figure 3: What flipping means geometrically, redrawing the two plots the week 3 practical solutions use to define it (p6 for the point, p7 for the line) side by side in one frame. Left: flipPoint negates both coordinates, so (-1,2) lands at (1,-2) - a 180-degree rotation about the origin, not a reflection in either axis. Right: flipLine is just that applied to both endpoints, sending the blue line (2,3)-(4,1) to the red line (-2,-3)-(-4,-1). The colours are the sheet’s.

On Point:

public Line createLine(Point end) {
    return new Line(this, end);
}

public Point flipPoint() {
    return new Point(x * -1, y * -1);
}

On Line:

public Point middle() {
    return new Point((start.getX() + end.getX()) / 2,
            (start.getY() + end.getY()) / 2);
}

public Line flipLine() {
    return new Line(start.flipPoint(), end.flipPoint());
}

Each of the four is a one-liner because the layer beneath it already exists: createLine hands this to a constructor, flipLine is flipPoint applied twice, middle is arithmetic on accessors. This is the payoff for having written Point properly first.

Note flipLine does not mutate — consistent with flipPoint and movePoint, and inconsistent with moveStart/moveEnd, which do. The class ends up with both conventions in it; the sheet does not reconcile them.

Question 5 — Polynomials (bonus)

A polynomial function specifies lines and curves on a Cartesian plane in terms of its coefficients:

Figure 4: The four example polynomials plotted in the week 3 practical solutions p8, redrawn with the sheet’s own colour coding and its full a + bx + cx^2 spellings alongside the collapsed forms. The point of the figure is that a straight line, a horizontal line and a parabola are all the same object here - only the three coefficients differ. The colour-keyed equation list is placed inside the figure rather than beside it as the sheet does.

In general a polynomial function has the form

\[f(x) = a_0 + a_1x + a_2x^2 + \dots + a_{n-1}x^{n-1} + a_nx^n\]

where \(a_0 \dots a_n\) are its coefficients. For this exercise it is restricted to \(f(x) = a + bx + cx^2\).

Write a Polynomial class represented by its coefficients, with constructors Polynomial() (giving \(f(x) = 0\)), Polynomial(float a), Polynomial(float a, float b), Polynomial(float a, float b, float c), plus:

  • float valueAt(float x) — the value of the polynomial at \(x\).
  • Polynomial add(Polynomial other) — a new Polynomial for \(f_1(x) + f_2(x) = (a_1 + a_2) + (b_1 + b_2)x + (c_1 + c_2)x^2\).

For \(f(x) = 1 + 2x\), what is \(f(3)\)?

\(f(3) = 1 + 2 \times 3 = 7\).

The model answer stores a float[] from the start, so it already solves the challenge below; the four “restricted” constructors are just convenience wrappers over one array:

import java.util.StringJoiner;

public class Polynomial {
    private final float[] coefficients;

    public Polynomial() { coefficients = new float[]{0}; }
    public Polynomial(float a) { coefficients = new float[]{a}; }
    public Polynomial(float a, float b) { coefficients = new float[]{a, b}; }
    public Polynomial(float a, float b, float c) { coefficients = new float[]{a, b, c}; }
    public Polynomial(float[] coefficients) { this.coefficients = coefficients; }

    private static float index(float[] coefficients, int index) {
        /* The value of coefficients with index greater than
         * the maximum index of the polynomial is 0. */
        if (index >= coefficients.length) {
            return 0;
        }
        return coefficients[index];
    }

    public Polynomial add(Polynomial other) {
        int max = Math.max(coefficients.length, other.coefficients.length);
        float[] newCoefficients = new float[max];
        for (int i = 0; i < max; i++) {
            newCoefficients[i] = index(coefficients, i)
                    + index(other.coefficients, i);
        }
        return new Polynomial(newCoefficients);
    }

    public float valueAt(float x) {
        float v = 0;
        float xpower = 1;
        for (int i = 0; i < coefficients.length; i++) {
            /* xpower = x^i */
            v += coefficients[i] * xpower;
            xpower *= x;
        }
        return v;
    }

    @Override
    public String toString() {
        StringJoiner builder = new StringJoiner(" + ");
        for (int i = 0; i < coefficients.length; i++) {
            builder.add(coefficients[i] + "x^" + i);
        }
        return builder.toString();
    }
}

Three things the model answer is doing on purpose:

  • private static float index(...) exists so add can read past the end of the shorter array without an if in the loop body — a coefficient that isn’t stored is \(0\). Without it, add would need a length check per term.
  • valueAt carries xpower along instead of calling Math.pow(x, i) each iteration: one multiply per term rather than a power computation per term. (Recognisably Horner-adjacent, though the sheet does not name it.)
  • coefficients is final, so a Polynomial cannot be re-pointed at a different coefficient array after construction — which is what lets add safely return a new instance rather than worrying about shared state. Note the Polynomial(float[]) constructor still stores the caller’s array by reference, so the contents are not protected; see java-mutability.

toString uses StringJoiner(" + "), which inserts the separator only between items — so a one-term polynomial prints without a trailing +.

Challenge — representing the unrestricted \(f(x) = a_0 + a_1x + \dots + a_nx^n\) for any \(n \geq 0\) needs no new code: valueAt, add and toString are all written against coefficients.length, and the Polynomial(float[]) constructor already accepts an array of any length.

Testing it end to end

The sheet’s own Main sweeps each polynomial across \(x \in [-10, 10)\) and prints the line, which is how you check Figure 4 by eye rather than by trust:

public class Main {
    private static void testPoints(Polynomial p) {
        for (int x = -10; x < 10; x++) {
            System.out.print(p.valueAt(x) + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Point p1 = new Point();
        Point p2 = p1.movePoint(4, 5);

        System.out.println(p1);
        System.out.println(p2);

        Line line = new Line(p1, p2);
        System.out.println(line);

        Polynomial acrossZero = new Polynomial();
        testPoints(acrossZero);

        Polynomial acrossTwo = new Polynomial(2);
        testPoints(acrossTwo);

        Polynomial diag = new Polynomial(1, 2);
        testPoints(diag);

        Polynomial slope = new Polynomial(2, -2);
        testPoints(slope);

        Polynomial parab = new Polynomial(1, 0, 0);
        testPoints(parab);

        System.out.println(parab);
        System.out.println(slope);
    }
}

Note new Polynomial(1, 0, 0) is named parab but is \(f(x) = 1\), a flat line — the coefficients are in ascending order (\(a\), then \(b\), then \(c\)), so the parabola would be new Polynomial(0, 0, 1). (That reading is mine, not the sheet’s; the sheet prints the listing without comment. It is a good illustration of why toString is worth writing: running this prints 1.0x^0 + 0.0x^1 + 0.0x^2 and the mistake is visible immediately.)

Stack Heap and Class Design

Applied class exercises for week 3, covering 2026-03-12-object-oriented-programming-ii and reinforcing java-mutability (why reference types behave differently from primitives when passed to methods). The class has two halves: sketching the runtime call stack and object heap to explain reference behaviour, and using that same “an object is a thing with fields” view to argue for a better class design.

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "1"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).

How to draw a stack/heap sketch

The sketches use a fixed vocabulary. Learn it before attempting the questions, because it is the form the answers are expected in:

  • a stack frame is the method’s name in bold above a two-column table, one row per local — parameters count as locals and get a row;
  • a primitive value is written straight into the value cell (3, 0, 1);
  • a reference is a filled dot in the value cell, with a black arrow to the object it names;
  • a heap array is a plain box holding the array literal, e.g. {3, 2, 3};
  • a heap object is a box with the class name in a bold header and one name/value row per field;
  • frames whose call has already returned are greyed out, and it is not necessary to include them at all;
  • frames are stacked with main at the top and each deeper call beneath it.

Two aliases pointing at one box is the whole point of the notation: it is what makes “the same object seen through two names” visible on paper.

The warm-up: aliasing an array

The whole exercise is motivated by a function whose return value surprises people:

static int[] reverse() {
    int[] first = {1, 2, 3};
    int[] second = first;

    int last = first[2];
    second[0] = last;
    second[1] = first[1];
    second[2] = first[0];

    return second;
}

This returns {3, 2, 3}, not {3, 2, 1}.

Figure 5: The stack and heap for the warm-up reverse() function. One stack frame, four rows, and a single heap array: first, second and the returned value are three names for one box, which is why writing through second is visible when read back through first. A filled dot with a black arrow is a reference; a primitive’s value is written in its cell.

int[] second = first; copies the reference, not the array. So there is exactly one array on the heap, and the three assignments all write into it:

step array afterwards
last = first[2] {1, 2, 3}, last == 3
second[0] = last {3, 2, 3}
second[1] = first[1] {3, 2, 3} (writes 2 over 2)
second[2] = first[0] {3, 2, 3} — first[0] is now 3, not the original 1

The last line is where the aliasing bites: by the time it runs, first[0] has already been overwritten. If second were an independent copy, the last line would read the untouched 1 and the function would return {3, 2, 1}, an actual reverse.

Question 1 — Tracing the call stack and heap

Understanding the runtime call stack and object heap clarifies unexpected behaviour of reference types. Consider:

class Counter {
    private int number;

    public Counter() { this.reset(); }
    public void increment(int amount) { this.number += amount; }
    public void increment() { this.number++; }
    public void reset() { this.number = 0; }
    public int getValue() { return this.number; }
}

class DebugMe {
    static void f(Counter counter, int param) {
        counter.increment();
        param++;
    }

    public static void main(String[] args) {
        Counter first = new Counter();
        int second = 0;
        f(first, second);
        System.out.println(first.getValue());
        System.out.println(second);
    }
}

Task 0 is to sketch the state of the call stack and heap just before f finishes executing; Task 1 is to say what main prints.

What does main print (first line, then second line)?

First line →

Second line →

Figure 6: Task 0’s answer: the state just before f returns. main sits above f; args and first hold references (dots) into the heap, second holds the primitive 0. first and counter point at the SAME Counter object, whose number field already reads 1. The increment frame is greyed because that call has already returned; such frames need not be drawn at all.

Read the answer straight off the picture:

  • first and counter are two references to one Counter object. counter.increment() inside f mutates that shared object, so the change is visible through first after f returns — first.getValue() prints 1.
  • param is an int, passed by value. param++ increments f’s own copy (the frame shows param at 1) and leaves main’s second at 0 — so the second line prints 0.

That is the general rule this class exists to fix in place: mutating an object through a reference parameter is visible to the caller; reassigning or incrementing a primitive parameter is not. (Reassigning a reference parameter — counter = new Counter() inside f — would likewise be invisible to main; Java passes the reference itself by value.)

args still gets a row and still points at a heap array, drawn {} because the program was run with no command-line arguments.

Question 2 — Designing a Vertex class

The Triangle class represents a triangle as a 2D array of coordinates: vertexes[0] is the three x-coordinates, vertexes[1] the three y-coordinates.

Figure 7: The triangle the exercise is about: vertices A, B, C with the interior angles alpha, beta, gamma and the sides a, b, c opposite them, beside the matrix form of the representation - one row of x-coordinates over one row of y-coordinates, which is exactly the double[][] the Triangle class stores.

The three-double constructor takes the side lengths \(a\), \(b\), \(c\) of Figure 7, not coordinates, and places the triangle in the plane for you:

public class Triangle {
    private double[][] vertexes;

    private static double square(double number) {
        return number * number;
    }

    public Triangle(double a, double b, double c) {
        double dividend = (square(a) - square(b) - square(c));
        double cx = dividend / (-2 * c);
        double cy = Math.sqrt(square(b) - square(cx));
        // the above just calculates the position of a third vertex
        // you do not need to understand it

        this.vertexes = new double[][]{
            // array of x-coordinates
            new double[]{0, c, cx},
            // array of y-coordinates
            new double[]{0, 0, cy}
        };
    }

    public Triangle(double[][] vertexes) {
        this.vertexes = vertexes;
    }

    private double distance(double x1, double x2, double y1, double y2) {
        return Math.sqrt(square(x1 - x2) + square(y1 - y2));
    }

    public double perimeter() {
        double x0 = vertexes[0][0];
        double x1 = vertexes[0][1];
        double x2 = vertexes[0][2];
        double y0 = vertexes[1][0];
        double y1 = vertexes[1][1];
        double y2 = vertexes[1][2];
        return distance(x0, y0, x1, y1) + distance(x1, y1, x2, y2)
                + distance(x2, y2, x0, y0);
    }

    public Triangle scale(double multiplier) {
        double[][] scaledUp = new double[2][3];
        for (int x = 0; x < 2; x++) {
            for (int y = 0; y < 3; y++) {
                scaledUp[x][y] = vertexes[x][y] * multiplier;
            }
        }
        return new Triangle(scaledUp);
    }
}

Design a Vertex class (signatures only, no implementation needed) that could simplify this — a triangle is really a collection of three vertices, each with an x and a y coordinate.

Only the signatures are designed, in shorthand: name, parameter types without parameter names, and a trailing comment.

class Vertex {
    Vertex(); // Construct a new vertex at (0, 0)
    Vertex(double, double);
    double distance(Vertex); // distance to another vertex
    Vertex scale(double); // multiply the coordinates by the given amount
}

Triangle is then rewritten on top of it. Either a Vertex[] or three Vertex member variables would do; the version below takes the second option, even though the question phrases the constructor as Triangle(Vertex[]):

public class Triangle {
    private Vertex a;
    private Vertex b;
    private Vertex c;

    public Triangle(double a, double b, double c) {
        double dividend = (square(a) - square(b) - square(c));
        double cx = dividend / (-2 * c);
        double cy = Math.sqrt(square(b) - square(cx));

        this.a = new Vertex();
        this.b = new Vertex(c, 0);
        this.c = new Vertex(cx, cy);
    }

    public Triangle(Vertex a, Vertex b, Vertex c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public Triangle(double[][] vertexes) {
        this.a = new Vertex(vertexes[0][0], vertexes[1][0]);
        this.b = new Vertex(vertexes[0][1], vertexes[1][1]);
        this.c = new Vertex(vertexes[0][2], vertexes[1][2]);
    }

    public double perimeter() {
        return a.distance(b) + b.distance(c) + c.distance(a);
    }

    public Triangle scale(double multiplier) {
        return new Triangle(a.scale(multiplier), b.scale(multiplier),
                c.scale(multiplier));
    }
}

perimeter() collapses from six local variables and three four-argument calls to one line, and scale from a nested loop over anonymous indices to one call per vertex. Introducing Vertex moves the x/y bookkeeping into a single-responsibility class, so Triangle’s own methods read as “distance between vertices” and “scale each vertex” rather than juggling raw array indices — the cohesion argument taken up properly in java-cohesion-and-coupling.

Two things about the original listing:

  • The three-argument constructor is the law of cosines. With \(\mathcal{A}\) at the origin and \(\mathcal{B}\) at \((c, 0)\), cx \(= (b^2 + c^2 - a^2) / 2c = b\cos\alpha\) and cy \(=\sqrt{b^2 - cx^2}\), i.e. \(\mathcal{C}\)’s coordinates. \(\mathcal{A}\) is at \((0,0)\), and the code writes new double[]{0, c, cx} for the x row, so \(\mathcal{B}\) has y-coordinate 0 and x-coordinate c.
  • perimeter() does not actually compute the perimeter. distance is declared (double x1, double x2, double y1, double y2) — both x’s, then both y’s — but every call passes coordinates point-wise: distance(x0, y0, x1, y1) binds x2 to y0 and y1 to x1, so the result is \(\sqrt{(x_0 - y_0)^2 + (x_1 - y_1)^2}\). That is a live bug, and it is caused by exactly the thing the exercise is arguing against: an argument list of four bare doubles carries no information about which number is an x and which is a y. The Vertex rewrite makes the same mistake impossible to write, because a.distance(b) has nowhere to put a coordinate in the wrong slot.

Question 3 — Recursive call stack (bonus)

class Reverser {
    static void reverse(int[] arr) {
        int n = arr.length;

        if (n == 1) {
            return;
        }

        // copy [1..n - 1] into rest
        int[] rest = new int[n - 1];
        for (int i = 1; i < n; i++) {
            rest[i - 1] = arr[i];
        }

        arr[n - 1] = arr[0];

        reverse(rest);
    }

    public static void main(String[] args) {
        int[] numbers = {42, 24, 11};
        reverse(numbers);
    }
}

Sketch the state of the call stack and heap just prior to the third call to reverse.

“Just prior to the third call” means two reverse frames are already live and neither has returned, so all three frames are drawn solid:

Figure 8: Task 4’s answer: the stack and heap immediately before the third call to reverse. Three live frames, four heap arrays. Each call’s rest becomes the next call’s arr - which is why the second and third boxes each have two arrows into them - while main’s numbers and the first call’s arr are two names for one array that has already been written to.

Reading the trace off the figure:

call arr on entry rest built arr[n-1] = arr[0] leaves arr as
1st {42, 24, 11} {24, 11} {42, 24, 42}
2nd {24, 11} {11} {24, 24}
3rd {11} — (n == 1, returns) {11}

Two structural points the picture makes:

  • rest is a fresh array each time. main’s numbers and the first call’s arr are the same box (one arrow each into {42, 24, 42}), but every deeper call works on a copy. Only the top frame’s write ever reaches numbers.
  • Reverser.reverse does not reverse anything. After main returns, numbers is {42, 24, 42} — the 42 has been copied over the 11 and nothing has moved. Each call writes its own first element into its own last slot and then hands a copy to the next call, so every write below the first frame lands in an array nobody keeps a reference to. The call stack sketch is what makes that visible; reading the source alone, the recursion looks plausible.

The base case is n == 1, so an empty array never terminates it — reverse(new int[0]) reaches new int[n - 1] with n == 0 and throws NegativeArraySizeException. A base case of n <= 1 would be the safer guard, the same widening move the week 5 practical makes for RecursiveFibonacci — see week5-lab-debugging.

Reference material

Java Abstraction

Introduced in 2026-03-05-object-oriented-programming-i (Lecture, Week 2).

What is abstraction?

The ability to hide complex implementation details and expose only the essential behaviours. In Java, abstraction is often implemented using interfaces and abstract classes — both define methods that must be implemented by subclasses, providing a contract that specifies what operations can be performed on an object without specifying how those operations are implemented.

Interfaces

  • An interface is a group of related methods with empty bodies.
  • An interface defines a contract that implementing classes must fulfil.
  • To access the interface methods, the interface must be implemented — and a class can implement multiple interfaces if required.

Interfaces provide abstraction in Java by defining behaviour without specifying implementation.

public interface PaymentProcessor {
    void processPayment(double amount);
}

Any payment processor must have a processPayment() method. Two classes take the interface up, each with its own body for that one method:

public class PayPalProcessor implements PaymentProcessor {
    @Override
    public void processPayment(double amount) {
        System.out.println("Processing PayPal payment: " + amount);
    }
}

public class StripeProcessor implements PaymentProcessor {
    @Override
    public void processPayment(double amount) {
        System.out.println("Processing Stripe payment: " + amount);
    }
}

and the caller is written against the interface, never against either class:

public class Main {
    public static void main(String[] args) {
        PaymentProcessor processor = new PayPalProcessor();
        processor.processPayment(100);
    }
}

The declared type of processor is PaymentProcessor, so Main can only call what the interface promises: the program only interacts with the interface. Swapping new PayPalProcessor() for new StripeProcessor() is therefore a one-line change: it changes what runs without touching anything else in Main.

Figure 9: Main depends on the PaymentProcessor interface, not on either implementation - which is what makes swapping PayPal for Stripe a one-line change. Each rectangle is labelled with its Java keyword and lists its members as + lines. A solid arrow with a solid head means uses. A dashed arrow with an open head means implements and runs from the implementer to the interface. The client is on the left and the abstraction in the centre.

An interface in Java represents an abstraction. It defines a set of behaviours that classes must implement, but it does not define how those behaviours are implemented. The implementation details are hidden inside the classes that implement the interface.

Abstract classes

  • An abstract class is a class that cannot be instantiated.
  • It can contain both abstract methods and fully implemented methods.
  • The abstract keyword is used to declare abstract classes and methods.
  • Subclasses must implement all abstract methods.

One qualification to the first bullet: an instance of an abstract class can be created using an anonymous class. The two statements are consistent. The ban is on new Payment(), while new Payment() { ... } instantiates an anonymous subclass rather than Payment itself.

public abstract class Payment {
    public void validateTransaction() {
        System.out.println("Validating transaction...");
    }

    abstract void processPayment(double amount);
}

That class defines common behaviour for every payment (validateTransaction), and does NOT define how a payment is processed. A subclass supplies the missing half:

public class PayPalPayment extends Payment {
    @Override
    public void processPayment(double amount) {
        System.out.println("Processing PayPal payment: $" + amount);
    }
}

public class Main {
    public static void main(String[] args) {
        Payment payment = new PayPalPayment();

        payment.validateTransaction();
        payment.processPayment(150.0);
    }
}

The abstract class defines the common behaviour of all payments while leaving the specific logic to subclasses. The two calls in main do different things structurally: validateTransaction() runs the body inherited from Payment, while processPayment() runs the body PayPalPayment had to supply.

Interfaces vs abstract classes

A homework / self-study item in Week 2, taken up in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3).

  • Use an interface to define a capability or contract, e.g. Flyable, Runnable, Payable. A class can implement multiple interfaces.
  • Use an abstract class to define a shared base implementation (common behaviour), e.g. an Animal abstract class shared by Dog and Cat. A class can only extend one (super)class.
abstract class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
    public abstract void makeSound();
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat Meows");
    }
}

A class can combine both: extend at most one abstract/concrete class, while implementing as many interfaces as needed:

class Dog extends Animal implements Runnable, Swimmable
class Duck extends Animal implements Flyable, Swimmable

Both mechanisms lean on the same machinery as java-inheritance — the @Override annotation and identical method signatures — and both pay off in Week 3 as java-polymorphism.

Java Casting

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). See also java-primitive-and-reference-types and week4-tutorial-method-dispatch-and-casting.

Casting is the process of converting a variable from one data type to another. There are two kinds: primitive casting, between the built-in numeric types, and reference casting, up and down an inheritance hierarchy.

Primitive casting

Set as self-study (homework). The reading is w3schools’ type casting page.

  • Widening — converting a smaller type to a larger type size: byte -> short -> char -> int -> long -> float -> double.
  • Narrowing — converting a larger type to a smaller size type: double -> float -> long -> int -> char -> short -> byte.

Figure 10: The two primitive conversion chains on a single axis: the narrowing chain is exactly the widening chain reversed. Widening is implicit; narrowing needs an explicit cast.

An example of a narrowing cast: long floatToLong = (long) inputFloat;.

Reference casting

  • Upcasting (implicit) — casting a subclass reference to a superclass reference.
  • Downcasting (explicit) — casting a superclass reference back to a subclass reference.

The two directions are defined against a class hierarchy: up the tree is upcasting, down the tree is downcasting.

Figure 11: The class hierarchy that upcasting and downcasting move along, with ‘Is a’ / ‘Is an’ edge labels and the up/down casting axis at the right. Object sits at the root because every class implicitly extends it.

Upcasting

Upcasting is done implicitly and is always safe: every Cat really is an Animal, so no check and no cast syntax is needed. In the assignment below the Cat is treated as an Animal:

public class Animal {
    public void makeSound() { System.out.println("Animal makes a sound"); }
}
public class Cat extends Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
}

Animal myAnimal = new Cat(); // upcasting: Cat is treated as an Animal
myAnimal.makeSound();        // Outputs: Cat meows

After the upcast, the declared type narrows what you may call, but the object still decides which body runs. That is java-polymorphism’s runtime dispatch, and it is why the line above prints Cat meows rather than Animal makes a sound.

Downcasting

Before downcasting, you must ensure the object is an instance of the subclass using the instanceof operator. The cast is written explicitly, and it is the only way to reach members that exist on the subclass but not the superclass:

public class Cat extends Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
    public void climb() { System.out.println("I can climb trees"); }
}

public class DownCasting {
    public static void main(String[] args) {
        Animal myAnimal = new Cat();     // upcasting

        if (myAnimal instanceof Cat) {
            Cat myCat = (Cat) myAnimal;  // Downcasting
            myCat.climb();               // access methods specific to cat
        }
    }
}

The instanceof guard is mandatory because an unguarded bad downcast is not a compile error: it compiles and throws ClassCastException at run time (see java-exceptions).

Additional reading: upcasting and downcasting in Java.

Every class implicitly extends Object

Worked question: what is the parent of class Student, a class with no extends clause at all?

public class Student {
    public void study() {
        System.out.println("CSSE2002");
    }
}

The answer is Object, the root of the Java class hierarchy and the top box of Figure 11. So every reference type can be upcast to Object, and a container declared over Object will hold anything. Getting a specific type back out of one means downcasting, which is the problem java-generics exists to remove.

Java Cohesion and Coupling

Introduced in 2026-04-02-refactoring (Lecture, Week 6, Part 2). Practised in week10-tutorial-coupling-and-cohesion.

Modularization

The process of dividing a large system (a monolith) into smaller, more manageable pieces that can be worked on and tested independently before being reassembled into the final product. This raises the question everything below answers: what if the resulting modules are highly dependent on each other? Cutting a monolith into pieces buys nothing if every piece still has to know about every other one. The left panel of the coupling figure below shows exactly that failure: six modules tangled together with arrows in all directions.

Two measures separate a real decomposition from a nominal one: coupling (how much the modules depend on each other) and cohesion (how well the contents of one module belong together).

Coupling

The degree of interdependence between different modules, classes, or components of a system.

  • High coupling — strong interconnections, where a change in one module can cascade through others.
  • Low coupling — greater independence and isolation between modules.

Figure 12: High versus low coupling. Left: every module talks directly to several others, so a change in any one can reach any other. Right: the same six modules each talk only to a shared interface — the grey bar — so nothing propagates further than that bar. A module is a wireframe cube, and its colour only tells the modules apart; a dependency is a teal double-headed arrow. The tangle of arrows on the left is schematic — the count is the point, not which cube joins which.

Levels of coupling (tightly → loosely coupled)

  1. Content — one class directly manipulates another’s data (e.g. public fields instead of private).
  2. Common — sharing access to the same global data/variables.
  3. External — sharing something imposed by an external source, e.g. a data format.
  4. Control — one class controls what happens in another by passing it information/instructions.
  5. Stamp — sharing a data structure, but each class only needs access to a select part of it.
  6. Data — sharing data through means such as parameter passing in methods.
  7. None — no dependency at all (most loosely coupled).

The list is ordered, and the order is the assessable part: the same two classes can be joined in any of these ways, and the further down the list you can get, the less a change in one can force a change in the other.

Figure 13: The coupling-levels ladder. Most tightly coupled at the top, least at the bottom, with the arrow running down from tightly coupled (needy) to loosely coupled (independent).

Worked classification examples

Four snippets, each with the same question: what type of coupling do these methods have? Each answer is reasoned from the definitions above.

public void sinh(int x) {...}
public void cosh(int x) {...}
public void tanh(int x) {
    return sinh(x) / cosh(x);
}

tanh only interacts with sinh/cosh by passing/receiving simple parameters — data coupling.

public class R { int x, y, z; char a, b, c; }
public static void compute(R r) {
    return r.x * r.y; // only touches x and y
}

compute is handed the whole R object but only needs two of its six fields — stamp coupling.

public static void compute(R r) {
    return r.x * r.y * r.z / r.a + r.b + r.c; // uses every field
}

Here every field of R is actually used, so passing the whole object is fully justified — this is just data coupling via a composite value, not stamp coupling (contrast with the previous example, which only used part of the structure).

public static runReport(String name, int age, String phone, Date birth, String address) {...}

Five separate simple parameters — still data coupling, though a long parameter list like this is itself often a separate code smell (see java-refactoring) worth considering bundling into an object.

Cohesion

The degree of interrelatedness and focus among the elements within a module, class, or component.

  • High cohesion — elements are closely related and contribute collectively to one specific functionality.
  • Low cohesion — elements are less focused, serving multiple unrelated purposes.

Asked of a class, cohesion comes down to two questions: how well do the parts of the class (state and methods) fit together? and do they all contribute to a single, clear purpose?

High cohesion is preferable. (Low cohesion usually indicates that a class should be split.)

Figure 14: Low versus high cohesion. The same twelve elements in both panels: on the left the four kinds are scattered across the grid, on the right each kind is gathered into one module. Colour means kind only, and each high-cohesion group is enclosed by a rectangle in that group’s own colour. This figure says nothing about coupling — it is only about what sits inside one module. The good case is again on the right.

Levels of cohesion (low → high)

  1. Coincidental — elements grouped arbitrarily, with no clear relationship.
  2. Temporal — elements grouped because they execute at the same time/phase.
  3. Procedural — elements grouped by their involvement in a specific sequence of steps.
  4. Communicational — elements work together to manipulate a shared data structure.
  5. Sequential — elements organised in a linear sequence, where one’s output is the next’s input.
  6. Functional — elements grouped around a single, specific functionality or task (most cohesive).

Worked example

public void performTasks(int[] numbers, String text) {
    // Task 1: sum the numbers
    int sum = 0;
    for (int num : numbers) { sum += num; }
    System.out.println("Sum of numbers: " + sum);

    // Task 2: reverse the text
    StringBuilder reversedText = new StringBuilder();
    for (int i = text.length() - 1; i >= 0; i--) { reversedText.append(text.charAt(i)); }
    System.out.println("Reversed text: " + reversedText);
}

Summing numbers and reversing text share no real purpose — they’re only in the same method because they happen to run one after another. This is low (coincidental, or at best temporal) cohesion, and a sign performTasks should be split into two focused methods.

Is this class cohesive?

A Car class contains: Fuel, Steering, Speed, Route planner, Public holiday calculator.

Fuel/Steering/Speed are all core to a car’s own physical behaviour, but a route planner and (especially) a public-holiday calculator are unrelated concerns bolted onto the class — this is low cohesion, and a sign the class is trying to do too much (a “God class”); the unrelated pieces should be split into their own classes.

Considerations

  • Classes should be highly cohesive — a single, easily understood concept.
  • Classes should have loose coupling to each other — this reduces overall system complexity.

Good modularization (high cohesion, low coupling) groups tightly-interconnected elements together into the same module and minimises connections between modules, unlike bad modularization, where connections are scattered across module boundaries with no clear grouping. The figure below makes this precise, because both panels are the same system — the same ten elements and the same fifteen dependencies — grouped into modules two different ways:

Figure 15: Bad versus good modularization. Both panels draw the same ten elements and the same fifteen dependencies; only the assignment of elements to modules A, B and C differs. Left: 5 dependencies fall inside a module and 10 cross a boundary. Right: 11 fall inside and only 4 cross. Nothing was rewritten to achieve that — the code is identical, the grouping is not.

Read off the figure, the two measures are the same count seen from opposite sides: a dependency that stays inside a module is cohesion, and a dependency that leaves one is coupling. Maximising the first and minimising the second is one decision — where to draw the boundaries — which is why the goal is always stated as a pair.

Java Encapsulation

Introduced in 2026-03-05-object-oriented-programming-i (Lecture, Week 2).

Classes and objects

  • A class describes the contents of the objects that belong to it: an aggregate of data fields (properties) plus the operations (methods) defined on them.
  • An object is an element (instance) of a class; objects have the behaviours of their class. The object is the actual component of a running program, while the class specifies how instances are created and how they behave.

Figure 16: One Student class, three Student objects: the class fixes the member variables and methods, each object carries its own values for them. Each arrow is one new Student(…) call creating an object. anu’s average is rounded to 76.6.

Encapsulation

Encapsulation is the process of bundling code (methods/member functions) and data (member variables) together into a single unit — a class. It restricts direct access to some of an object’s components, preventing the accidental modification of data.

Figure 17: What a class is made of, and how it is written as a diagram. Left: a member-variable compartment above a methods compartment, the two braced together as the class. Right: the same idea as a two-compartment box, attributes above operations, with the class name above the box. The attribute list and the operation list in the box do not quite match (email against getAddress).

The Java that box stands for:

public class Person {
    private String name;
    private int age;
    private String email;
    private String[] phoneNumber;

    public Person(String name, int age, String email, String[] phoneNumber) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
    public String getEmail() { return email; }
    public String[] getPhoneNumber() { return phoneNumber; }
}

The box and the code do not match exactly: the box lists an email attribute but a getAddress() operation (the box has no address attribute and no getEmail() operation, while the code has email and getEmail() and no address at all), and the box spells the array field phoneNumbers where the code spells it phoneNumber. The intended mapping is the obvious one — one private attribute per - line, one public method per + line, the constructor in the operations compartment with no return type.

Constructors

A constructor is a special method invoked when an object of the class is created (via new):

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        Person person = new Person("John", 20);
        System.out.println("The name of the person is " + person.name);
    }
}

If a class has no constructor, the Java compiler automatically creates a default constructor. Take the same class with the constructor deleted and new Person() called instead — it still compiles, because the compiler supplies the no-argument constructor. name is never assigned, so the println would print null.

public class Person {
    private String name;
    private int age;

    public static void main(String[] args) {
        Person person = new Person();
        System.out.println("The name of the person is " + person.name);
    }
}

Notes on constructors:

  • Constructors are invoked implicitly when objects are instantiated.
  • The constructor’s name MUST be the same as the class.
  • A Java constructor must not have a return type.
  • If a class does not have a constructor, the compiler creates a default constructor. This happens at compile time, not at run time: the compiler emits it into the class file.
  • A constructor can be overloaded but can not be overridden.

Access modifiers

Access modifiers set the accessibility (visibility) of classes, interfaces, properties, methods, constructors, and data members:

Modifier Accessible from
private Only within the declaring class
public Anywhere
protected Same package, plus subclasses (see java-inheritance)
(default, no keyword) Only within the same package

The same BankAccount under three of the four:

private — the field cannot be touched from outside the class, so this does not compile:

public class BankAccount {
    private double balance;
    private String accountNumber;
    private String accountHolder;
    private double interestRate;
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.balance = 1000.0;   // compile error
    }
}

java: balance has private access in Week02.OOP.AccessModifers.BankAccount

public — change balance to public double balance; and the assignment that would not compile above is now legal. Add System.out.println("Balance: " + account.balance); to Main and it prints Balance: 1000.0.

default (no keyword) — drop the modifier entirely (double balance;) and, because Main is in the same package, it also compiles and prints Balance: 1000.0. The difference from public only shows up across a package boundary.

protected is homework: read DigitalOcean’s Java access modifiers tutorial. It is accessible within the same package as well as from subclasses. The subclass clause is what makes protected wider than default access, because it reaches subclasses in other packages too.

Getters and setters

Getter and setter methods provide controlled access to an object’s private fields, keeping its internal representation hidden from the outside world:

  • Getters (accessors) retrieve the value of a private field from outside the class.
  • Setters (mutators) set/update the value of a private field from outside the class.
public class BankAccount {
    private double balance;
    private String accountNumber;

    public BankAccount(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public double getBalance() { return balance; }
    public void setBalance(double balance) { this.balance = balance; }
    public String getAccountNumber() { return accountNumber; }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("111000");
        account.setBalance(10000);
        System.out.println("Balance: " + account.getBalance());
        System.out.println("Account number: " + account.getAccountNumber());
    }
}

The example is asymmetric: balance gets both a getter and a setter, accountNumber gets only a getter. Whether a field is writable from outside is a per-field design decision, not something you owe every field.

The static keyword

static is a non-access modifier for methods and attributes:

  • Static methods/attributes can be accessed without creating an object of the class.
  • Useful in memory management; can be applied to variables, methods, blocks, and nested classes.
  • In procedural programming the same keyword means something different: it marks a variable or function whose scope is limited to the file it is declared in.

Static variables (class variables) are shared among all instances of a class — useful for constants and shared properties:

class BankAccount {
    public static int totalAccounts = 0;

    private double balance;
    private String accountNumber;
    private String accountHolder;

    public BankAccount(double balance, String accountNumber, String accountHolder) {
        this.balance = balance;
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
    }

    public String getAccountNumber() { return accountNumber; }
    public double getBalance() { return balance; }
    public String getAccountHolder() { return accountHolder; }
}

Static methods can be called without creating an instance, but cannot access non-static (instance) variables or methods directly:

class Bank {
    static double interestRate = 5.0;

    static double calculateInterest(double balance, int years) {
        return (balance * interestRate * years) / 100;
    }
}

class BankAccount {
    private String accountHolder;
    private double balance;

    BankAccount(String name, double balance) {
        this.accountHolder = name;
        this.balance = balance;
    }

    void showInterest(int years) {
        double interest = Bank.calculateInterest(balance, years);
        System.out.println(accountHolder + " earns $" + interest + " in " + years + " years.");
    }
}

The call site is the point of the example: it reads Bank.calculateInterest(...) — on the class, not on an instance — and because calculateInterest is static it cannot reach any account’s balance itself, so the balance has to be handed to it as an argument. The static field interestRate, by contrast, it can read directly, because that field belongs to the class too.

Class invariants

A class invariant specifies a condition (or set of conditions) that should always be true throughout the life of an object — used to ensure a system remains in a valid state. Put more precisely, it is a constraint that must hold at every stable point in time during the life of an object. A class invariant:

  1. Must be established after the class constructor.
  2. May be assumed as a precondition of each method (excluding the constructor).
  3. Must be established after each method call.
class Counter {
    private int count;
    public Counter() { count = 0; }
    public void increment() { count = count + 1; }
}
// Invariant: count >= 0

Trace the three rules against Counter: the constructor sets count = 0, which establishes count >= 0; increment may assume count >= 0 on entry; and since it only ever adds 1, count >= 0 still holds on exit. Nothing else can reach count, because it is private — which is what makes the invariant enforceable at all rather than merely hoped for.

Invariants complement preconditions (what must be true before a method executes) and postconditions (what must be true after) — together these define a contract for how a method or function should behave. Pre/postconditions themselves are in java-specification and java-hoare-logic; see also week8-tutorial-class-invariants.

Protecting invariants

The Counter example does not show how an invariant can be broken from outside. Guarding against that is what makes the definition enforceable rather than merely stated; see also week8-tutorial-class-invariants and the defensive-programming material in java-specification.

A specification can claim an invariant while the implementation still allows it to be broken. Two common leaks:

  1. Public fields — a directly-mutable field lets any caller bypass the class entirely and violate the invariant. Fix: make the field private.
  2. Returning an internal reference — a getter that returns its internal mutable collection/object directly hands the caller a way to mutate it from outside, bypassing any checks the class’s own methods perform. Fix: return a defensive copy:
private List<String> files;

public List<String> getFiles() {
    return new ArrayList<>(files); // copy, not the internal reference
}

Preserving the invariant may also require adding preconditions to methods that could otherwise violate it (e.g. rejecting an addition that wouldn’t satisfy the invariant), or, when a method is likely to be called by code outside your control, defensively throwing an exception (e.g. IllegalArgumentException/IllegalStateException) rather than relying purely on the precondition contract (see java-specification — Defensive programming).

Method signatures

A method signature is a method’s unique identifier: its name plus its parameter types. The return type and the parameter names do not count towards the signature, and a signature MUST be unique within a class:

public void print() { ... }              // signature: print()
public void print(int parameter) { ... } // signature: print(int)

Worked question — is this allowed?

public class Action {
    public Boot fish(int strength, int rodLength) { ... }
    public Fish fish(int strength, int polLength) { ... }
}

No. Both methods have the signature fish(int, int). The differing return types (Boot vs Fish) and the differing parameter names (rodLength vs polLength) are exactly the two things a signature ignores, so the class will not compile. This same rule is what makes overriding work in java-inheritance: an override must repeat the superclass method’s signature exactly, or it is a new overload rather than an override.

Java Mutability

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). Builds on java-encapsulation.

Mutable vs immutable classes

Objects in Java can either change their state after creation or remain fixed forever.

Two types of class design:

  • Mutable class — object state can change after creation.
  • Immutable class — object state cannot change after creation.

Mutable

State is reachable through setters, so it can change at any point in the object’s life:

public class Person {
    private String name;
    private int age;

    public void setName(String name) { this.name = name; }
    public void setAge(int age) { this.age = age; }
}
class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Alice");
        p.setAge(20);

        p.setAge(30);   // state changed
    }
}

This object can change at any time.

Immutable

The immutable version changes four things at once: the class is final, both fields are final, the values arrive through the constructor, and there are no setters — only getters.

public final class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}
class Main {
    public static void main(String[] args) {
        Person p1 = new Person("Alice", 20);
        Person p2 = new Person("Bob", 30);
        System.out.println(p1.getName() + " " + p1.getAge());
    }
}

Changing a value now means constructing a new object, not mutating the old one.

Why final on the class

A subclass can introduce mutability (Effective Java (2nd ed.), Item 16, page 78). If the class is subclassable, a subclass can add mutable state or override methods to return values that vary, so callers can no longer rely on “an instance of this type never changes”. Marking the class final is what forecloses that.

Arrays and lists break naive immutability

Even if a class looks immutable, it may not be.

final on an array field only prevents reassigning the reference. It does nothing to protect the array’s contents, and a getter that returns the field hands the caller a live handle on the object’s own state:

public final class Person {
    private final String name;
    private final String[] phoneNumbers;

    public Person(String name) {
        this.name = name;
        this.phoneNumbers = new String[]{"111", "222"};
    }

    public String getName() { return name; }

    public String[] getPhoneNumbers() { return phoneNumbers; }
}
class Main {
    public static void main(String[] args) {
        Person person = new Person("John");
        person.getPhoneNumbers()[0] = "999999";

        System.out.println(person.getPhoneNumbers()[0]);   // 999999
    }
}

Every field is private final and there is not a setter in sight, yet the object’s state changed. The rule:

  • final for arrays means the reference cannot change, not the contents.
  • final prevents reassigning the array:
this.phoneNumbers = new String[]{"123"}; // NOT allowed if already assigned

Defensive copying

To protect mutable objects, create copies — on the way in and on the way out, so neither the constructor’s caller nor the getter’s caller keeps a handle on the field (Effective Java, Item 50: “Make defensive copies when needed”):

public final class Person {
    private final String name;
    private final String[] phoneNumbers;

    public Person(String Name, String[] phoneNumbers) {
        this.name = Name;
        this.phoneNumbers = phoneNumbers.clone();   // defensive copy
    }

    public String[] getPhoneNumbers() {
        return phoneNumbers.clone();                // defensive copy
    }
}

Figure 18: Why a class whose getter returns its array field is not immutable, and what .clone() changes. Left: the field and the getter’s return value are the same array, so the caller’s write lands in the object’s state. Right: the getter hands out a copy, so the write lands somewhere the object does not care about.

clone() on an array is a shallow copy — it duplicates the row of references, not the objects they point at. That is enough here because String is itself immutable, but a Person[] of mutable Person objects would still leak.

Java Polymorphism

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). Practised in week4-tutorial-method-dispatch-and-casting.

What is polymorphism?

From the Greek “poly” (many) and “morphe” (form). In programming, it allows the same method call to produce different behaviour depending on the object that executes it.

There are three named kinds. The first two differ in when the method body is chosen; the third is about what types a call site will accept.

Figure 19: The two selection mechanisms. Left: overloading is resolved by the compiler from the argument’s compile-time type, so the choice is fixed once the file compiles. Right: overriding is resolved by the JVM from the object actually on the other end of the reference; the arrow from myAnimal.makeSound() to Dog.makeSound() means the call dispatches to that method.

Compile-time polymorphism (method overloading)

Method overloading occurs when multiple methods have the same name but different parameter lists (different type, number, or both). The method to be executed is determined at compile time based on the method signature.

Which one runs is decided from the signature (see java-encapsulation) before the program ever runs:

public class CompPolymorphism {
    static String print(int value) {
        return "number";
    }
    static String print(String value) {
        return "text";
    }

    public static void main(String[] args) {
        System.out.println(print(21));    // number
        System.out.println(print("21"));  // text
    }
}

Runtime polymorphism (dynamic method dispatch)

  • Runtime polymorphism is also known as dynamic method dispatch.
  • It occurs when the method that gets executed is determined at runtime based on the actual object type, not the variable type.
  • It is implemented through method overriding — when a subclass provides a specific implementation for a method already defined in its superclass, the subclass’s method is the overridden method (see java-inheritance).

The rule:

The subclass’s overriding method executes, regardless of the compile-time type of the subclass instance. — Effective Java

The example below reassigns the same variable: nothing about the variable changed, only the object it points at.

public class Animal {
    public void makeSound() { System.out.println("Animal makes a sound"); }
}
public class Cat extends Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
}
public class Dog extends Animal {
    @Override public void makeSound() { System.out.println("Dog barks"); }
}
public class TestPolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();
        myAnimal.makeSound();   // Dog barks

        myAnimal = new Cat();
        myAnimal.makeSound();   // Cat meows
    }
}

Even though the object type is Animal, the Dog version of makeSound() runs because the actual object is Dog.

Subtype polymorphism

  • Subtype polymorphism occurs when objects of different subclasses can be treated as objects of a common superclass or interface.
  • This is possible because subclasses are subtypes of their superclass.
  • It is achieved through inheritance (extends) or interface implementation (implements).
  • It allows code to work with the abstraction (supertype) instead of specific implementations.

The rule the whole idea rests on:

A subclass object can be used anywhere a superclass is expected.

Where runtime polymorphism is about which body runs, subtype polymorphism is about what a call site will accept: performAnimalSound is written once against Animal and never mentions Dog or Cat.

public class TestSubtypePolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();

        performAnimalSound(myAnimal);   // a Dog object
    }

    public static void performAnimalSound(Animal animal) {
        animal.makeSound();             // Outputs: Dog barks
    }
}

The same method works unchanged when the supertype is an interface rather than a superclass. Any class that implements the interface can be passed:

public interface Animal {
    void makeSound();
}

public class Cat implements Animal {
    @Override public void makeSound() { System.out.println("Cat meows"); }
}
public class Dog implements Animal {
    @Override public void makeSound() { System.out.println("Dog barks"); }
}
public class TestSubtypePolymorphism {
    public static void main(String[] args) {
        performAnimalSound(new Dog());
        performAnimalSound(new Cat());
    }

    public static void performAnimalSound(Animal animal) {
        animal.makeSound();
    }
}

Choosing between the two supertypes is the interface-vs-abstract-class question — see java-abstraction.

How it connects to casting

Assigning new Dog() to an Animal variable is an implicit upcast (java-casting). That is why the declared type restricts what you may call (myAnimal.climb() will not compile even when the object is a Cat) while the actual object still decides what runs — the left and right halves of Figure 19 are the same reference seen from the compiler’s side and the JVM’s side.

Java Specification

Introduced in 2026-03-12-object-oriented-programming-ii (Lecture, Week 3). Extended in 2026-03-19-exceptions and formalised later in java-hoare-logic; pre/postconditions come back as class invariants in week8-tutorial-class-invariants and as the substitution principle in week9-tutorial-substitution-principle-and-pre-post-conditions.

The order below: Javadoc → restrictiveness → generality → formality → contracts → defensive programming.

Javadoc

  • Ordinary comments: // and /* ... */.
  • Javadoc comments:
    • begin with /** — note the second *; the Javadoc generator ignores all other comments;
    • end with */;
    • must sit immediately above the thing being documented;
    • use tags beginning with @;
    • some tags take parameters, some just text.

A worked example:

/**
 * Calculates a sum by combining the hash code of the provided string
 * and the long value of the provided float.
 *
 * @param inputString the input string whose hash code will be used
 * @param inputFloat  the float value to be converted to long and combined with the string hash code
 * @return a long value representing the sum of the string's hash code and the long value of the float
 */
public long doCalculation(String inputString, float inputFloat){
    long floatToLong = (long) inputFloat;

    // Combine the hash code of the string with the float-to-long value
    long result = inputString.hashCode() + floatToLong;

    return result;
}

Tags

Methods:

Tag Argument Meaning
@param varname … Describe a parameter for a method
@return … Describe the return value
@throws ExceptionType … Describe when a particular type of exception is thrown by the method
@requires Precondition Specify the assumptions for a method to execute properly
@ensures Postcondition Specify the effects of executing the method

Classes:

Tag Argument Meaning
@author authorname Specify the author of the class
@copyright … Provide details on who owns copyright
NoteThe contract tags are spelled two ways

The tag table above and the findMax example use @requires / @ensures. The formal withdraw specification and the contract examples use @require / @ensure, with no s. The same split runs across the course as a whole. Neither form is declared canonical, and the examples below use both. @requires and @ensures are not standard Javadoc tags. They are the course’s own convention layered on top of it, which is why the generator will not do anything special with them.

What makes a good specification

Ideally a specification will:

  • Allow the use of a method by only reading the specification, not by reading and understanding the implementation.
  • Allow a method to be re-implemented without requiring changes to any methods that use it.

And it should:

  • Rule out all implementations that are unacceptable — i.e. be sufficiently restrictive.
  • Not preclude acceptable implementations — i.e. be sufficiently general.
  • Be easy for users (programmers) to understand — i.e. be clear.

The next three sections take one method, search, and fail each of those three tests in turn.

Restrictiveness — keep out incorrect implementations

/**
 * Returns an index (i) of ar such that
 * ar[i] == x, if any.
 */
public int search(int[] ar, int x) {…}

This does not say what happens if x is not in ar. It is tempting to assume the obvious answer, but the specification doesn’t say, so don’t assume. By its silence, the specification allows any value to be returned. So a return of 1 or 0 could mean “It’s at index 1/0” or “I didn’t find it”.

Adding the missing case makes it better, still bad:

/**
 * Returns an index (i) of ar such that
 * ar[i] == x, if any
 * else, return -1
 */
public int search(int[] ar, int x) {…}

Suppose x appears in ar multiple times. There is nothing in the spec that requires:

  • that you will get the lowest index;
  • that you will get the same answer running multiple times.

The specification is non-deterministic.

Figure 20: With the spec worded as ‘returns an index i such that ar[i] == x’, both cells holding 3 are legal answers, and nothing forbids the method returning a different one on each call. That is what makes the specification non-deterministic.

Generality — allow acceptable alternative versions

The obvious fix for the non-determinism is to say which index you get. Saying it like this, however, is a bad example:

/**
 *  Examine ar[0], ar[1], ... in turn and
 *  return the index of the
 *  first one that is equal to x, if any,
 *  else return -1
 */
public int search(int[] ar, int x) {…}

It is restrictive enough, but it over-commits: it describes how the method walks the array. A forward-scanning implementation goes with it (see the warning below before trusting this listing):

public int search(int[] ar, int x) {
    int found = -1;
    for (int i = 0; i < ar.length; i++) {
        if (ar[i] == x) {
            found = i;
        }
    }
    return found;
}

The consequence of the over-committed wording shows when the loop is run the other way:

public int search(int[] ar, int x) {
    int found = -1;
    for (int i = ar.length-1; i >= 0; i--) {
        if (ar[i] == x) {
            found = i;
        }
    }
    return found;
}

Scanning backwards and keeping the last match found is the smallest matching index — the answer the spec asks for — but the specification said ar[0], ar[1], ... in turn, so this version does not satisfy the specification. A perfectly good implementation has been outlawed by wording that was never about the outcome.

Even if you think that is the most natural way to do something, that doesn’t mean it should be part of the specification.

Specs should describe what happens, not how.

Rewritten to talk about the result only, the specification now accepts the backward implementation:

/**
 * Return smallest index (i) of ar such that
 * ar[i] == x, if any,
 * else return -1
 */
public int search(int[] ar, int x) {…}
WarningThe forward listing does not return the smallest index

The backward scan above returns the smallest index, so it satisfies the rewritten spec. The forward scan from earlier does not:

for (int i = 0; i < ar.length; i++) {
    if (ar[i] == x) { found = i; }
}
return found;

That loop overwrites found on every match, so it returns the largest matching index, not the smallest — and not the first one either, which is what the earlier spec asked for. On ar = [1,3,4,2,3,5] with x = 3 it returns 4 where both specs want 1. The forward and backward listings only agree when x occurs at most once. A forward scan that satisfies the spec has to stop at the first match:

for (int i = 0; i < ar.length; i++) {
    if (ar[i] == x) { return i; }
}
return -1;

Clarity

  • A specification should facilitate communication between people.
  • Two ways in which communication could fail:
    • the reader doesn’t understand;
    • the reader only thinks they understand.
  • Clarity can be improved by being as concise as possible. Long specs are:
    • more likely to contain errors/contradictions,
    • less likely to be read properly,
    • more likely to be misunderstood.
  • Redundancy may help — but be clear that it is redundant, by using e.g. “e.g.” or “i.e.”.

Four specs to judge

Four one-line specifications. The question for each is whether it is a good specification.

/**
 * Sorts the given array.
 */
public void sort(int[] ar) {...}
/**
 * Calculate x to the power of two with Math.pow.
 */
public int square(int x) {...}
/**
 * Returns the list of ResourceContainers stored by this instance.
 */
public List<ResourceContainer> getResources() {...}
/**
 * Calculate the nth value of the fibonacci sequence.
 */
public long fib(int n) {...}

Applying the three criteria (restrictive, general, clear):

  • sort — under-restrictive. Ascending or descending? In place, or is the return of void supposed to imply in place? What about equal elements?
  • square — over-general in one direction and over-specific in another: it names Math.pow, which is a how, exactly the generality failure above; and it never says what happens on overflow.
  • getResources — the mutability trap from java-mutability. Is the returned List the instance’s own list, so that the caller can add to it, or a copy? Restrictiveness: the spec’s silence permits either, so no caller can safely do anything with it.
  • fib — under-restrictive on the domain and on the indexing convention. Is fib(0) 0 or 1? What happens for negative n, or for an n whose answer overflows long?

Formality

Specifications of software range in formality:

  • informal — e.g. normal comments;
  • semi-formal — structured English documentation, e.g. using Javadoc tags;
  • formal — mathematical constraints, e.g. using Java syntax for boolean expressions.

Here is the same method specified three times, once at each level.

Informal:

/**
 * Withdraws an amount from this account and
 * returns how much is left.
 */
public int withdraw(int amount) {...}

This leaves three things open: what happens when amount is negative, what happens when amount is bigger than the balance, and whether the balance is changed when there is a failure.

Semi-formal — structured English, one tag per obligation:

/**
 * Withdraw an amount from this account.
 *
 * @param amount the amount to withdraw, must be a positive integer.
 * @return the new balance after the withdrawal.
 * @throws IllegalArgumentException if the amount is negative.
 * @throws InsufficientFundsException if the amount is greater than the current balance.
 */
public int withdraw(int amount) {...}

Formal — boolean expressions in Java syntax, with \old(...) naming the value an expression had before the call:

/**
 * Withdraws an amount from this account.
 *
 * @require amount >= 0
 * @require amount <= getBalance()
 * @ensure getBalance() == \old(getBalance()) - amount
 */
public int withdraw(int amount) {...}

There is no @throws in the formal version. The failure cases have not been forgotten: they have been moved into the caller’s obligations. The next section covers this.

Contracts

Specifications can be written using contracts:

/**
 * [Description of method's behaviour]
 *
 * @require [Precondition]
 * @ensure [Postcondition]
 */
  • If the code calling the method satisfies the precondition, then the method guarantees to satisfy the postcondition.
  • If the code calling the method does not satisfy the precondition, then the method guarantees nothing — any behaviour is allowed.

Programming with contracts

\result names the returned value inside a postcondition:

/**
 * Withdraws an amount from this account.
 *
 * @require amount >= 0
 * @require amount <= getBalance()
 * @ensure getBalance == \old(getBalance()) - amount
 * @ensure \result == getBalance()
 */
public int withdraw(int amount) {
    // no need to check the conditions
}
int balance = myAccount.withdraw(amt);

In the first @ensure, getBalance is written without the parentheses it has in the formal specification above.

It is up to the calling code to make sure it fulfils its side of the contract, i.e. 0 <= amt <= myAccount.getBalance().

The method body carries no validation at all, and the call site carries no error handling — the postcondition is unconditional, so balance is always meaningful.

Programming without contracts

The same method written defensively instead, with the failure folded into the return value:

/**
 * Withdraw an amount from this account.
 *
 * @param amount The amount to withdraw.
 * @return The balance of this account after
 *         the withdrawal successfully occurs,
 *         or -1 if it fails.
 */
public int withdraw(int amount) {
    if (amount < 0) {
        return -1;
    }
    if (balance < amount) {
        return -1;
    }
}
int balance = myAccount.withdraw(amt);
If(balance == -1) {
   ...
}

The method body shows only the two checks; the success path is left out. The call site writes If with a capital where Java needs if.

The cost is visible on both sides: the method now checks twice on every call, and every call site has to branch on a sentinel. It also re-introduces exactly the restrictiveness problem from search — -1 has to mean both “a balance” and “it failed”.

Defensive programming

Definition (Defensive Programming) Explicitly checking for invalid inputs and bad situations, ensuring the software does not behave dangerously regardless of input.

Sooner or later someone will call the method without checking the precondition. Particularly when dealing with external input sources or when guarding critical resources, it may be better to be defensive outside the wall and use contracts inside it.

Figure 21: Defensive outside the wall, contracts inside it: validate defensively where untrusted input crosses into the system, and rely on contracts for the internal calls behind that boundary, so the check happens once rather than at every hop. The gate box is the findMax method worked through below.

Worked example: findMax

The starting point, with no specification and no checks:

public int findMax(int[] numbers) {
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < numbers.length-1; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    return max;
}

Documented, and with the defensive check added:

/**
 * Finds the maximum value in the given array of integers.
 *
 * @param numbers An array of integers from which the maximum value is to be found.
 * @return The maximum value in the array.
 * @throws IllegalArgumentException if the array is null or empty.
 *
 * @requires numbers != null && numbers.length > 0
 *    - The array must not be null.
 *    - The array must contain at least one element.
 *
 * @ensures
 *    - The method returns the maximum value found in the array.
 *
 */
public int findMax(int[] numbers) {
    if (numbers == null || numbers.length == 0) {
        throw new IllegalArgumentException("Array must not be null or empty.");
    }

    int max = Integer.MIN_VALUE;
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    return max;
}

This version writes the precondition down as @requires, promises an exception in @throws for callers who break it anyway, and then checks it in the body — belt and braces, which is the whole point of being defensive at a boundary. Without the check, a null array throws NullPointerException and an empty array silently returns Integer.MIN_VALUE as if that were a real maximum.

TipThe loop bound differs between the two versions

The first version loops i < numbers.length-1 and the documented version loops i < numbers.length. The first version therefore never examines the last element, so findMax(new int[]{1, 2, 9}) returns 2. No specification was attached to the first version, so nothing about it was wrong according to its spec, because it did not have one.

Further reading

Key takeaways

  • A specification describes the contract between a method and its client.
  • It explains what the method does, not how it is implemented.
  • A good specification clearly states:
    • Preconditions — conditions that must be true before the method is called;
    • Postconditions — conditions that will be true after the method finishes successfully;
    • Side effects — any additional changes the method makes to the system.
  • Clear specifications make code easier to understand, use, and maintain.