CSSE2002 — Week 4 Notes
Exceptions
See csse2002 for course logistics. A supplementary lecture on java-version-control also ran this week.
Code samples are in the course CodeCamp playlist and Git repo.
Outline
- Exceptions: what an exception is, the hierarchy, checked vs unchecked,
try/catch,throw,throws,finally, custom exceptions. - Specification: Javadoc → Restrictiveness → Generality → Formality → Contracts → Defensive Programming.
Exceptions
See java-exceptions — the exception hierarchy, checked vs unchecked exceptions, try/catch/throw/throws/finally, and custom exceptions. The finally exercise (Good Morning / hello / world) is worked there; week5-tutorial-exceptions then pushes the same tracing into nested blocks.
Specification
This repeats Week 3’s material: Javadoc, restrictiveness, generality, clarity, formality, contracts, defensive programming. See java-specification, which also has an early-return variant of the search generality example and an Effective Java citation for defensive programming/doc comments.
The rest of this section covers the examples that are not in that note.
The search array — why “an index” isn’t a specification
Restrictiveness on search, in three steps. The first spec:
/**
* Returns an index (i) of ar such that ar[i] == x, if any.
*/
public int search(int[] ar, int x) { … }This is a bad specification. It is silent about x not being in ar, and by its silence it allows any value to be returned. A return of 1 or 0 could equally mean “it’s at index 1/0” or “I didn’t find it”.
Adding else, return -1 is better but still bad. This array is why:
Figure 1: The array ar is the counterexample to the improved spec: 3 sits at both index 1 and index 4, so a specification asking only for an index i with ar[i] == x lets an implementation return either, and lets it return a different one on each call.
Nothing in that spec requires that you get the lowest index, or that you get the same answer running multiple times. Only “return the smallest index (i) of ar such that ar[i] == x, if any, else return -1” fixes both. Two different implementations can both satisfy that wording, which is the generality example.
Worked: is this a good specification?
Four specs, each judged against the three criteria: restrictive, general, clear.
/**
* Sorts the given array.
*/
public void sort(int[] ar) { … }Not restrictive enough: ascending or descending is never stated, so both satisfy it.
/**
* Calculate x to the power of two with Math.pow.
*/
public int square(int x) { … }Not general enough — the classic generality failure. It names an implementation (Math.pow), so it describes how rather than what, and an x * x implementation that computes exactly the same answer technically violates it.
/**
* Returns the list of ResourceContainers stored by this instance.
*/
public List<ResourceContainer> getResources() { … }Not restrictive enough about aliasing: it doesn’t say whether the caller gets the internal list or a copy, so it doesn’t say whether adding to the returned list changes the object — see java-mutability.
/**
* Calculate the nth value of the fibonacci sequence.
*/
public long fib(int n) { … }Not clear enough: it doesn’t fix the indexing (is fib(0) 0 or 1?), and says nothing about negative n or about n large enough to overflow long.
Contracts — the caller’s obligation, and \result
The contract form of withdraw carries a postcondition on the return value as well as on the state. The call site follows it:
/**
* 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);The method body needs no checks at all, because it is up to the calling code to make sure it fulfils its side of the contract, i.e. 0 <= amt <= myAccount.getBalance(). Written without a contract, the same method checks both conditions itself and returns the sentinel -1 on failure, which pushes an if (balance == -1) { … } into every call site.
The tags are spelt @require/@ensure here and @requires/@ensures elsewhere. Both spellings are used across the course. In the first @ensure line the left-hand getBalance is the call getBalance().
findMax — the undefended version, then the defended one
Defensive programming, before and after. The undefended version is code only, with no Javadoc:
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;
}The defended version adds the full specification (@param, @return, @throws IllegalArgumentException if the array is null or empty, @requires numbers != null && numbers.length > 0, @ensures the maximum is returned) and the guard clause that throws it. That version is in java-specification.
The loop bound also changes between the two versions, from i < numbers.length-1 to i < numbers.length. The undefended version never examines the last element.
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 its preconditions (true before the call), postconditions (true after it finishes successfully), and side effects (any other changes it makes to the system).
- Clear specifications make code easier to understand, use, and maintain.
Further reading: Oracle’s Preconditions, Postconditions, and Class Invariants and Assertions guides, plus Effective Java (3rd Edition) Item 56, “Write doc comments for all exposed API elements”.
Method Dispatch and Casting
Applied class exercises for week 4, covering java-polymorphism (dynamic method dispatch) and java-casting in more depth.
On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "Car.topSpeed()"), 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).
The five rules of method dispatch
Method dispatch follows five rules. Everything else in the class is an application of them:
- The compiler deduces an apparent type (also called a compile-time type) for each object, using type information from variable and method declarations.
- Each object also has an actual type (also called a runtime type), obtained when it is created by
new: the type of the class that constructs it. - The compiler ensures the apparent type it deduces is always the actual type, or a superclass of the actual type.
- The compiler determines what calls are legal based on the object’s apparent type.
- Dispatching causes method calls to go to the object’s actual code — that is, the code provided by its actual type.
Figure 2: The two types every reference carries, and what each one decides, on the declaration C variable = new R();, where C is a superclass of R or is R. The apparent type C decides whether variable.method() is legal; the actual type R decides which code it runs.
Rules 4 and 5 are the whole exercise: legality is decided from the apparent type, the code that runs comes from the actual type. The two are settled at different times and can disagree.
Question 1 — Apparent type vs actual type
class Animal {
void eat() {...}
}
class Lion extends Animal {}
class Dog extends Animal implements Pet {
void eat() {...}
void eat(int howMuch) {...}
}
class Poodle extends Dog {}
interface Pet {}A diagram makes it easier to see how the classes are related and which method will be invoked:
Figure 3: The Question 1 hierarchy. Superclass above; a solid rectangle for a class and a dashed rectangle for an interface; the class name in bold serif over a rule, members below as + name(); a solid line for extends and a dashed line for implements, both with the same filled arrowhead. The SOLID diagrams draw implements with an open arrowhead instead.
What happens when you call simba.eat(200), given Lion simba = new Lion();?
simba’s apparent AND actual type is Lion, which has no eat(int) method (only the no-arg eat() inherited from Animal) — the compiler rejects the call outright, since legality is checked against the apparent type’s available methods (rule 4).
The full table, one line at a time:
| Statement | Outcome |
|---|---|
Dog evie = new Dog(); |
OK |
Animal animal = evie; |
OK (upcast, implicit) |
Lion mufasa = animal; |
Must be cast. Will fail (an Animal referencing a Dog is never a Lion). |
Dog harlee = animal; |
Must be cast. Will succeed — the cast is written out as if (animal instanceof Dog harlee) ... |
Poodle bruiser = evie; |
Must be cast. Will fail (evie’s actual type is Dog, not Poodle). |
Lion simba = new Lion(); |
OK |
Lion scar = new Poodle(); |
Will not compile — Poodle and Lion share no inheritance relationship. |
Pet charley = new Poodle(); |
OK (Poodle extends Dog, which implements Pet). |
Dog lassie = charley; |
Must be cast. Will succeed. |
Animal scooby = charley; |
Will not compile — Pet is not related to Animal (an interface doesn’t know about unrelated classes). |
simba.eat(); |
OK |
simba.eat(200); |
No method found — compile error. |
Task 0 — Draw the hierarchy
Draw a diagram which makes the code below easier to understand.
In the following, all classes, interfaces, and members are public, and many details have been omitted:
class Location {...}
interface RoadLegal {
int topSpeed();
boolean licenceRequired();
}
interface PublicTransport {
double calculateFare(Location start, Location end);
}
class Vehicle {
int travelTime(Location start, Location end) {...}
int topSpeed() {...}
}
class HumanPowered extends Vehicle {
int getWeight() {...}
int topSpeed() {...}
}
class Motorised extends Vehicle implements RoadLegal {
int travelTime(Location start, Location end) {...}
int topSpeed() {...}
boolean licenceRequired() {...}
}
class Skateboard extends HumanPowered {}
class Bicycle extends HumanPowered implements RoadLegal {
boolean licenceRequired() {...}
}
class Motorbike extends Motorised {
int topSpeed() {...}
int travelTime(Location location) {...} // overload, not an override
}
class Car extends Motorised {
int topSpeed() {...}
}
class Taxi extends Car {}
class Bus extends Motorised implements PublicTransport {
int topSpeed() {...}
double calculateFare(Location start, Location end) {...}
}Figure 4: Task 0’s answer. Same conventions as Figure 3: dashed rectangles are interfaces, solid lines are extends, dashed lines are implements, both with a filled arrowhead, superclass above. Only the methods each type actually declares are listed — that is what makes the dispatch questions answerable by eye. Location is drawn floating and unconnected. Motorbike declares travelTime(Location) — one argument — which is an overload of, not an override of, Vehicle.travelTime(Location, Location).
Two things to read off the picture before attempting anything else:
RoadLegalis reached twice by different routes — once throughMotorised, once directly fromBicycle. SoMotorbike,Car,Taxi,BusandBicycleare allRoadLegal, butSkateboardis not.BicycleimplementsRoadLegalyet declares onlylicenceRequired(). It satisfiestopSpeed()with the one it inherits fromHumanPowered.
Task 1 — Does it compile?
For the creation and usage of objects below, indicate whether the statements would compile or not. If it would not compile, explain why.
| # | Statement(s) | Verdict |
|---|---|---|
| 1 | Vehicle bus = new Bus(); |
Compiles, no error. Bus is implicitly upcast to Vehicle. |
| 2 | Motorised skateboard = new Skateboard(); |
Does not compile. There is no relationship between Motorised and Skateboard, so a Skateboard can never be an instance of Motorised. |
| 3 | Motorbike vehicle = new Vehicle(); |
Does not compile. Going from Vehicle to Motorbike is a downcast, so an explicit cast is required. |
| 4 | Motorised motorbike = new Motorbike();Location destination = new Location();motorbike.travelTime(destination); |
Does not compile. Motorised and its parent classes have no method matching the signature travelTime(Location). The one-argument overload exists only on Motorbike, and legality is judged from the apparent type. |
| 5 | Motorbike motorbike = new Motorbike();Location start = new Location();Location end = new Location();motorbike.travelTime(start, end); |
Compiles, no error. travelTime() is overloaded in Motorbike, so both the one- and two-Location versions are available through a Motorbike-typed variable. |
Bonus:
| # | Statement(s) | Verdict |
|---|---|---|
| 1 | Car car = new Taxi();Taxi taxi = car; |
Does not compile. Going from Car to Taxi is a downcast, so an explicit cast is required. |
| 2 | Vehicle bike = new Bicycle();bike.getWeight(); |
Does not compile. Vehicle has no method matching the signature getWeight() — it is declared on HumanPowered. |
| 3 | Motorised bus = new Bus();PublicTransport trip = bus;trip.calculateFare(start, end); |
Does not compile. Motorised cannot be implicitly cast into PublicTransport. |
Items 4 and 5 are the pair worth memorising. A Motorbike object really does have a one-argument travelTime — item 5 shows both overloads are reachable through a Motorbike-typed variable. Widen the variable to Motorised and the very same object stops accepting the call (item 4), because legality is judged from the apparent type and nothing above Motorbike declares that signature.
Task 2 — Which implementation is called?
For each, what method implementation is actually called? (Assume location1 and location2 are Location objects.)
Vehicle vehicle = new Taxi(); vehicle.topSpeed(); →
Vehicle vehicle = new Bicycle(); vehicle.topSpeed(); →
RoadLegal roadLegal = new Bicycle(); roadLegal.topSpeed(); →
Vehicle vehicle = new Motorbike(); vehicle.travelTime(location1, location2); →
| Call | Dispatches to |
|---|---|
Vehicle vehicle = new Taxi(); vehicle.topSpeed(); |
Car.topSpeed() |
Vehicle vehicle = new Bicycle(); vehicle.topSpeed(); |
HumanPowered.topSpeed() |
RoadLegal roadLegal = new Bicycle(); roadLegal.topSpeed(); |
HumanPowered.topSpeed() |
Vehicle vehicle = new Motorbike(); vehicle.travelTime(location1, location2); |
Motorised.travelTime(Location, Location) |
Read each one off Figure 4: start at the actual type and walk up until you find a box that lists the method.
Taxideclares nothing, sotopSpeed()comes fromCar.Bicycledeclares onlylicenceRequired(), sotopSpeed()comes fromHumanPowered— and this is unchanged when the apparent type is theRoadLegalinterface. Dispatch never consults the apparent type (rule 5).MotorbikeoverridestopSpeed()and overloadstravelTimewith a one-argument version, but never overrides the two-argument one, so that call lands onMotorised.
Casting — the three rules
In Java, when changing the apparent type of a value:
- If the new apparent type is a superclass of the old apparent type, the cast can be implicit.
- If the new apparent type is a subclass of the old apparent type, the cast should be performed via an
instanceofcheck. - If the new apparent type and old apparent type have no inheritance relationship, Java will refuse to compile.
Task 3 — instanceof: compiles? implicit?
Assume that xyz is an instance of class Xyz — e.g. bus is an instance of Bus. For each cast, indicate whether (1) it would compile and (2) it could be implicit.
| Expression | Compiles | Implicit | Why |
|---|---|---|---|
if (bus instanceof Vehicle vehicle) |
✓ | ✓ | Vehicle is a superclass of Bus — rule 1. |
if (car instanceof Taxi taxi) |
✓ | ✗ | Taxi is a subclass of Car, so it needs the runtime check — rule 2. |
if (motorised instanceof Bicycle bike) |
✗ | — | Motorised and Bicycle are siblings under Vehicle with no relationship — rule 3. |
if (motorbike instanceof RoadLegal legal) |
✓ | ✓ | Motorbike extends Motorised, which implements RoadLegal. |
if (taxi instanceof Vehicle vehicle) |
✓ | ✓ | Vehicle is a superclass all the way up the Taxi → Car → Motorised → Vehicle chain. |
The “Implicit” cell is left blank for the row that does not compile, rather than marked ✗ — there is nothing to decide once the code is rejected.
Task 4 — Where would an electric scooter fit?
If we wanted a class to represent an electric scooter, where would that fit in the hierarchy?
The answer is deliberately open; this is a discussion question. Not all models fit all circumstances, and single inheritance makes this one difficult.
An electric scooter is motorised and human-scale, road-legal in some jurisdictions and not others — and Java gives you exactly one superclass. The escape hatch the rest of the course teaches is to push the shared behaviour into interfaces rather than a class (see java-solid-principles on interface segregation, and week11-tutorial-dependency-inversion).
Where this reappears
The same two-phase rule — overload chosen at compile time from the static types, override resolved at run time from the actual type — comes back in revision Questions 19–21, worked with the BruceWayne/Batman/kapow example. See 2026-05-28-course-summary-and-exam-preparation and 2026-03-12-object-oriented-programming-ii.
Reference material
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 5: 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 6: 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 meowsAfter 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 6. 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 Exceptions
Introduced in 2026-03-19-exceptions (Lecture, Week 4, Part 1). Traced in depth in week5-tutorial-exceptions.
What is an exception?
An unexpected event that occurs during program execution, e.g.:
System.out.println(5 / 0); // Infinity??No — integer division by zero causes a java.lang.ArithmeticException: / by zero. Infinity is the tempting wrong answer: it is what floating-point division gives, not integer division.
Common causes:
- invalid user input
- loss of network connection
- physical limitations (out of disk memory)
- code errors
- opening an unavailable file
When an exception occurs within a method it creates an object — the exception object — which contains information about the exception. Effective Java (2017), Item 75, says to include failure-capture information in detail messages: that object is where the diagnostic information has to live.
We can catch the exception to handle it, and the catch block is where the program is put back into a usable state:
try {
System.out.println(5 / 0);
} catch (ArithmeticException e) {
System.out.println(e); // print out error message
//do something to recover
}Exception hierarchy
Figure 7: The exception hierarchy. Throwable is the root; Error and Exception sit beneath it; RuntimeException (unchecked) and IOException (checked) sit beneath Exception. Each connector joins the subclasses and points up to their parent. Which branch a class is on is what decides whether the compiler forces you to handle it, so this one picture settles the checked/unchecked question.
RuntimeException — unchecked
A runtime exception happens due to a programming error. Also known as unchecked exceptions: the compiler does not force you to handle them.
| Cause | Exception |
|---|---|
| Improper use of an API | IllegalArgumentException |
| Null pointer access | NullPointerException |
| Out-of-bounds array access | ArrayIndexOutOfBoundsException |
| Dividing a number by 0 | ArithmeticException |
IOException — checked
Also known as a checked exception: it is checked by the compiler at compile time, and the programmer is prompted to handle it.
| Cause | Exception |
|---|---|
| Trying to open a file that doesn’t exist | FileNotFoundException |
| Trying to read past the end of a file | EOFException |
| A connection attempt to a remote host fails | ConnectException |
Java exception handling
There are three mechanisms: the try…catch block, the throw and throws keywords, and the finally block.
try … catch
Place the code that might generate an exception inside the try block. Every try block is followed by a catch block.
int result;
try {
result = 5 / 0;
…
} catch (ArithmeticException e) {
System.out.println(e); // print out error message
result = Integer.MAX_VALUE; // Assign a default or fallback value
}- When an exception occurs, the rest of the code inside the
tryblock is skipped. - The
catchblock catches the exception and the statements inside thecatchblock are executed. - If none of the statements in the
tryblock generates an exception, thecatchblock is skipped.
Figure 8: The two paths through a try/catch/finally, and the fact that both of them end up in finally. This is the three numbered rules together with the finally rule, drawn as one picture: the exceptional path abandons the remaining statements of the try and enters catch, the normal path skips catch entirely, and neither can skip finally.
throw
The throw keyword is used to explicitly throw a single exception. Two examples:
public class Main {
public static void main(String[] args) {
divideByZero();
}
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
}public class Main {
public static void main(String[] args) {
checkEntry(17);
}
public static void checkEntry(int age) {
if (age < 18) {
throw new IllegalArgumentException("Access denied ");
}
else {
System.out.println("Access granted ");
}
}
}throw is used to manually trigger an error when your program detects something invalid, so it doesn’t continue in a bad state. That is the point of the whole keyword, and it is also the bridge to java-specification: throwing is how a method refuses input that breaks its precondition instead of limping on.
throws
The throws keyword declares the type of exceptions that might occur within the method, and it is used in the method declaration. The caller is then the one prompted to handle it:
public class ThrowsEx {
public static void main(String[] args) {
try {
findFile();
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void findFile() throws FileNotFoundException {
// code that may generate FileNotFoundException
File newFile = new File("file.txt");
FileInputStream stream = new FileInputStream(newFile);
}
}throw and throws are not two spellings of one thing: throw (statement, inside a body) raises an exception; throws (clause, in a signature) declares that one can escape. Only checked exceptions have to be declared — that is exactly what “checked by the compiler” buys you.
finally
- The
finallyblock is executed regardless of whether an exception is thrown. - The
finallyblock is optional.
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}Exercise — what will the following print?
try{
System.out.println("Good Morning");
throw new FileNotFoundException();
System.out.println("the earth says");
}catch (Exception e){
System.out.println("hello");
}finally {
System.out.println("world");
}Answer:
Good Morning
hello
world
Working through it against the rules above: "Good Morning" prints; the throw immediately abandons the rest of the try, so "the earth says" never prints; the catch parameter is Exception, and FileNotFoundException is an Exception, so this catch matches and "hello" prints; finally always runs, so "world" prints last.
As written this snippet would not actually compile. System.out.println("the earth says"); sits directly after an unconditional throw in the same block, and Java rejects that at compile time as an unreachable statement. Read it as a tracing exercise about the order of the three rules, not as something to paste into a file.
Custom exceptions
Define your own by extending Exception (or a subclass of it), then declare it with throws and raise it with throw:
public class MyCustomException extends Exception {
...
}
int myFunction() throws MyCustomException {
throw new MyCustomException();
}Worked example — ItemNotFoundException
The exception class gives a no-argument constructor with a fixed message and a second constructor taking a custom one, both delegating to super(...) — the Throwable message is the failure-capture information from Item 75:
public class ItemNotFoundException extends Exception{
public ItemNotFoundException(){
super("Item not found");
}
// Constructor that accepts a custom message
public ItemNotFoundException(String message) {
super(message);
}
}The class that uses it declares throws on the searching method and throws when the loop falls through without a match:
public class Store {
private List<String> items;
public Store() {
items = new ArrayList<>();
items.add("apple");
items.add("banana");
items.add("orange");
}
public String findItem(String itemName) throws ItemNotFoundException {
for (String item : items) {
if (item.equals(itemName)) {
return item;
}
}
throw new ItemNotFoundException("Item '" + itemName + "' not found in the list.");
}
public static void main(String[] args) {
Store store = new Store();
try {
String item = store.findItem("grape");
System.out.println("Found item: " + item);
} catch (ItemNotFoundException e) {
System.err.println(e.getMessage());
}
}
}findItem("grape") misses, so the try is abandoned at the call — "Found item: …" never prints — and the catch reports Item 'grape' not found in the list. on System.err.
Java Inheritance
Introduced in 2026-03-05-object-oriented-programming-i (Lecture, Week 2) — “things you have because your parents have them”.
Subclasses and superclasses
Inheritance allows creating a new class from an existing class:
- The new class is the subclass (child/derived class).
- The existing class it’s derived from is the superclass (parent/base class).
The running example is one Employee superclass with two subclasses:
Figure 9: The Employee inheritance example as a UML class diagram. Each box has three compartments (name / attributes / operations), with - for private and + for public, and constructors listed in the operations compartment with no return type. Generalisation is a solid line with a single unfilled triangle arrowhead entering the superclass.
This form is not a course-wide standard. The course draws inheritance in three ways: this UML three-compartment form with an unfilled triangle, a labelled box with a plain arrowhead, and a diagonal form with every edge labelled “Is a”. None of them is declared canonical. See csse2002-diagram-notation for the compartment, visibility and arrowhead conventions this figure uses.
Two things to read off the diagram before looking at any code:
nameandaddressare declaredprivateinEmployeeand are not repeated in either subclass. EveryContractEmployeecarries them, but the subclass’s own code cannot name them —privatemembers are not accessible in a subclass — which is what forces thesuper(...)call below.printDetails()appears in all three boxes. That repetition is the setup for method overriding.
(The diagram writes CalcWeeklyPay() with a capital C; the code calls the same method calculateWeeklyPay(). The code spelling is the one to trust.)
extends
extends is the keyword used to implement inheritance in Java:
public class Employee {
private String name;
private String address;
public Employee(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() { return name; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public String printDetails() { return name + " " + address; }
}
public class ContractEmployee extends Employee {
private double hourlyRate;
private int hoursWorked;
public ContractEmployee(String name, String address, double hourlyRate) {
super(name, address);
this.hourlyRate = hourlyRate;
this.hoursWorked = 0;
}
public void logHours(int hours) { this.hoursWorked += hours; }
public double calculateWeeklyPay() { return hourlyRate * hoursWorked; }
}From the diagram, the shape of FullTimeEmployee is private double monthlySalary, a constructor FullTimeEmployee(String name, String address, double monthlySalary), and calcMonthlyPay() / calcAnnualPay() both returning double.
The super keyword
super is used in a subclass to access superclass members — attributes, constructors and methods.
As a constructor call, super(name, address) runs Employee’s constructor first, so the inherited name and address are initialised before the subclass’s own constructor body runs. This is not merely tidy: name and address are private in Employee, so ContractEmployee has no other way to set them.
Method overriding
The subclass inherits the attributes and methods of its superclass. If the same method is defined in both the superclass and the subclass, the subclass’s version overrides the superclass’s version — and both MUST have the same method signature (see java-encapsulation; a different signature gives you an overload, not an override).
public class Employee {
...
public String printDetails() {
return name + " " + address;
}
}
public class ContractEmployee extends Employee {
...
@Override
public String printDetails() {
return "Role: Contract Employee, Hourly Rate: $" + hourlyRate
+ ", Hours Worked: " + hoursWorked;
}
}
public class FullTimeEmployee extends Employee {
@Override
public String printDetails() {
return "Role: Full-Time Employee, Monthly Salary: $" + monthlySalary;
}
}super in an override
The superclass’s method is still reachable after overriding it. super.methodName(...) calls the superclass’s version from inside the override, so the subclass can extend the inherited behaviour rather than replace it:
public class FullTimeEmployee extends Employee {
...
@Override
public String printDetails() {
return super.printDetails()
+ ", Role: Full-Time Employee, Monthly Salary: $" + monthlySalary;
}
}With Employee.printDetails() returning name + " " + address, this version prints the name and address and the role and salary, where the previous version threw the inherited half away.
Choosing whether Employee’s printDetails() or a subclass’s override actually runs for a given object is dynamic dispatch, taken up with polymorphism — see java-polymorphism and week4-tutorial-method-dispatch-and-casting.
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:
finalfor arrays means the reference cannot change, not the contents.finalprevents reassigning the array:
this.phoneNumbers = new String[]{"123"}; // NOT allowed if already assignedDefensive 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 10: 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 11: 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 11 are the same reference seen from the compiler’s side and the JVM’s side.
Java SOLID Principles
Introduced in 2026-04-02-refactoring (Lecture, Week 6, Part 3 — Single Responsibility and Open-Closed) and continued in 2026-04-16-solid-principles-ii (Lecture, Week 7 — Liskov Substitution, Interface Segregation, Dependency Inversion).
Why SOLID?
Large software tends to become:
- Rigid — difficult to change; even small changes require modifications across many parts of the codebase.
- Fragile — likely to break when changed, sometimes in parts of the codebase that appear unrelated to the change.
The SOLID principles (S-ingle responsibility, O-pen-closed, L-iskov substitution, I-nterface segregation, D-ependency inversion) are a set of guidelines — not rules — to help prevent rigidity and fragility. Many of the individual ideas predate the acronym; Robert Martin combined them in Design Principles and Design Patterns (2000).
Week 6 covers the first two: Single Responsibility and Open-closed.
Single Responsibility Principle (SRP)
There should never be more than one reason for a class to change.
Closely related to java-cohesion-and-coupling’s cohesion: cohesion is about how similar a class’s functionality is, while SRP is about the reasons for change. A “responsibility” is a reason for change — if you can think of more than one motive to change a class, it has more than one responsibility.
class Student {
private String name;
private List<Course> courses;
private double gpa;
public void enrollInCourse(Course course) { courses.add(course); }
public void calculateGPA() { /* ... */ }
public void printTranscript() { /* ... */ }
}This class has three reasons to change:
- Changing how to enrol to courses.
- Changing how overall GPAs are calculated.
- Changing how transcripts are generated.
Splitting each concern into its own class gives each one a single responsibility:
class Student {
private String name;
private List<Course> courses;
public void enrollInCourse(Course course) { courses.add(course); }
public List<Course> getCourses() { return courses; }
}
class GPACalculator {
public double calculateGPA(List<Course> courses) { /* ... */ }
}
class TranscriptPrinter {
public void printTranscript(Student student) { /* ... */ }
}Two details of the split are worth noticing. The gpa field is gone: it was a cached result of one of the three responsibilities, so it leaves with the responsibility, and GPACalculator.calculateGPA returns a value instead of assigning one. And Student gains getCourses(), because the two extracted classes now need the data from outside — the responsibilities separate cleanly, but they do not become independent.
The same shape, stated more briefly:
// Before // After
class Report { class ReportCalculator { }
void calculateData() {} class ReportSaver { }
void saveToFile() {} class ReportPrinter { }
void printReport() {}
}Calculating, saving and printing are three different reasons to change one Report class — a new output format, a new storage backend and a new formula are unrelated events — so they become three classes.
Homework. Check whether SRP improves memory management indirectly, by improving overall design structure — think about object creation, immutability (see java-mutability) and garbage collection.
Open-Closed Principle (OCP)
Components should be open for extension but closed for modification.
Introduced by Bertrand Meyer in Object Oriented Software Construction (1988): “if the open-closed principle is applied well, then further changes are achieved by adding new code, not by changing old code that already works”.
- Open for extension — a class’s behaviour can be extended to support changing requirements.
- Closed for modification — no one may change the behaviour of an existing class; it’s closed once it’s available for other modules to depend on.
A class is kept closed for modification by information hiding (see java-encapsulation).
Example: pluggable grading systems
The example picks up the GPACalculator extracted under SRP above, which assumes a single grading scheme:
class GPACalculator {
public double calculateGPA(List<Course> courses) {
double totalPoints = 0;
for (Course course : courses) {
totalPoints += course.getGradePoints();
}
return totalPoints / courses.size();
}
}Now a requirement arrives: the university needs to handle different grading systems, such as letter grades (A, B, C) and numerical grades (90, 80, 70). A first attempt branches on a gradeType string:
class GPACalculator {
public double calculateGPA(List<Course> courses, String gradeType) {
double totalPoints = 0;
if (gradeType.equals("Letter")) {
for (Course course : courses) {
totalPoints += convertLetterGradeToPoints(course.getLetterGrade());
}
} else if (gradeType.equals("Numeric")) {
for (Course course : courses) {
totalPoints += course.getNumericGrade();
}
}
return totalPoints / courses.size();
}
private double convertLetterGradeToPoints(String letterGrade) {
// Convert letter grade to GPA points logic
return 0;
}
}Three things carry the problem: the added String gradeType parameter, and the two string literals "Letter" and "Numeric". They are every place that has to be modified the next time a grading system is added, in a class that was supposed to be finished. The class is open for extension only by editing it, which is exactly what “closed for modification” forbids. (A gradeType string also reintroduces the Vehicle-style type switch from java-refactoring.)
Extracting the grading logic behind an interface makes GPACalculator open for extension (new GradingSystem implementations) without ever touching its own code again:
interface GradingSystem {
double getGradePoints(Course course);
}
class LetterGradingSystem implements GradingSystem {
@Override
public double getGradePoints(Course course) { /* convert letter grade to points */ return 0; }
}
class NumericGradingSystem implements GradingSystem {
@Override
public double getGradePoints(Course course) { return course.getNumericGrade(); }
}
class GPACalculator {
private GradingSystem gradingSystem;
public GPACalculator(GradingSystem gradingSystem) { this.gradingSystem = gradingSystem; }
public double calculateGPA(List<Course> courses) {
double totalPoints = 0;
for (Course course : courses) {
totalPoints += gradingSystem.getGradePoints(course);
}
return totalPoints / courses.size();
}
}The caller picks the grading system and hands it to the calculator:
public static void main(String[] args) {
List<Course> letterGradeCourses = new ArrayList<>();
letterGradeCourses.add(new Course("CS", "A"));
GradingSystem letterGradingSystem = new LetterGradingSystem();
GPACalculator gpaCalculator = new GPACalculator(letterGradingSystem);
System.out.println("GPA (Letter Grades): " + gpaCalculator.calculateGPA(letterGradeCourses));
}Figure 12: The open-closed refactoring of GPACalculator. GPACalculator uses only the GradingSystem interface; each concrete grading system implements it. A new scheme — pass/fail, say — is a fourth box on the bottom row with a fourth dashed arrow, and no existing box changes: that is ‘open for extension, closed for modification’ as a picture. Each label carries the Java keyword and members are listed as ‘+ m()’. A solid line with a solid head means ‘uses’, a dashed line with an open head means ‘implements’, and every arrow points from the depender to the thing depended upon. This is not UML, which would draw realisation as a hollow triangle.
What the refactoring bought:
GPACalculatordepends on the abstractionGradingSysteminstead of calculating grade points itself — which makes it open for extension (new grading systems) but closed for modification.- More grading systems can be added without changing the core logic of
GPACalculator. - The interface guarantees every grading system implements the same method (
getGradePoints()), making it easy to switch between them. maindemonstrates using eitherLetterGradingSystemorNumericGradingSystemby passing a different grading system to theGPACalculator.
Two arrows into an abstraction that nobody edits is also how the class stays closed: the calculator is closed for modification because the only thing it can see of a grading system is the interface. That is information hiding used structurally, and it is the same move as the Dependency Inversion Principle below; the constructor parameter here is dependency injection.
Liskov Substitution Principle (LSP)
Subclasses should be substitutable for their parent classes.
Defined by Barbara Liskov in a 1987 keynote: an instance of a subclass type can be used wherever an instance of a superclass type is expected, without breaking the correctness of the program:
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Mouse());
for (Animal animal : animals) {
animal.eat(new Food());
}Example violation
class Student {
protected List<Course> courses;
public double calculateGPA() {
double totalPoints = 0;
for (Course course : courses) {
totalPoints += course.getGradePoints();
}
return totalPoints / courses.size();
}
}
class PostgraduateStudent extends Student {
@Override
public double calculateGPA() {
throw new UnsupportedOperationException("Postgraduates have a different GPA system.");
}
}Code written against Student (e.g. calling calculateGPA() on every student in a list) will blow up the moment a PostgraduateStudent is substituted in — PostgraduateStudent is not actually usable wherever a Student is expected, so it violates LSP.
Substitution with contracts
Even when a subclass overrides a method with a different implementation, it must still honour the parent’s contract (see java-specification):
class Parent {
/**
* @requires x > 0
* @ensures \result > 'A' && \result < 'Z'
*/
char f(int x);
}Preconditions — suppose an overriding Child.f() can also handle negative numbers. Changing its precondition from x > 0 to x != 0 is fine: every input Parent.f() accepted (x > 0) is still accepted by Child.f() (x != 0), since \(x > 0 \Rightarrow x \neq 0\) — so the precondition became weaker (less strict), not stronger. Preconditions in a subclass must be no stronger than the superclass’s — they may be weaker or stay the same.
Postconditions — suppose Child.f() only ever returns 'K', 'L', or 'M'. A postcondition of \result > 'J' && \result < 'N' is fine: every result still satisfies the parent’s promise (\result > 'J' && \result < 'N' \Rightarrow \result > 'A' && \result < 'Z'), so the postcondition became stronger (more restrictive), which is allowed. Postconditions in a subclass must be no weaker than the superclass’s — they may be stronger or stay the same.
A subclass must not strengthen preconditions or weaken postconditions — it should accept everything the parent accepts, and still guarantee everything the parent guarantees.
Worked example
class One {
/**
* @require row != null && col != null && 0 < val && val < 100
* @ensure \result is the list of all of the positive
* integers n < val that appear in either row or col
*/
public List<Integer> calc(int[] row, int[] col, int val) { ... }
}
class Two extends One {
/**
* @require row != null && col != null && 0 < val &&
* val < 100 && row only contains positive integers
* @ensure \result is the list of all of the positive
* integers n < val that appear in either row or col
*/
@Override
public List<Integer> calc(int[] row, int[] col, int val) { ... }
}Two’s precondition adds an extra requirement (row only contains positive integers) that One never required — so One’s precondition does not imply Two’s: there are inputs One would accept (a row containing a negative number) that Two rejects. This strengthens the precondition and violates LSP: code written against One that happens to pass a negative-containing row would break if a Two were substituted in.
Homework variant: if Two’s postcondition is instead changed to return integers appearing in both row and col (rather than either), does this satisfy LSP? Reasoning it through: the guarantee changes from a union to an intersection, which for most inputs returns strictly fewer elements than One promised — that’s a weaker postcondition (some outputs a caller was guaranteed under One are no longer guaranteed under Two), which also violates LSP.
Interface Segregation Principle (ISP)
Many client-specific interfaces are better than one general-purpose interface.
Shrink interfaces to minimize incidental dependencies — large interfaces should be split into smaller ones, so implementing/using classes only need to be concerned about the methods that actually interest them.
class Z {
public void a() {...}
public void b() {...}
public void c() {...}
public void d() {...}
public void e() {...}
}
// A only uses a() and b(), B only uses c(), C only uses d() and e() ...
// ...but all three classes still depend on the whole of Z.This mirrors java-cohesion-and-coupling’s stamp coupling at the interface level: despite each client using only a small subset of Z, every client depends on all of Z — so a change to any part of Z risks affecting (and forcing a recompile/redeploy of) every client, even ones that never used the changed part. Splitting Z’s surface into focused interfaces removes those incidental dependencies:
interface AI { void a(); void b(); }
interface BI { void c(); }
interface CI { void d(); void e(); }
// Z implements AI, BI, CI; A depends only on AI, B only on BI, C only on CI.Dependency Inversion Principle (DIP)
Depend upon abstractions. Do not depend upon concretions.
Entities must depend on abstractions, not concretions: high-level modules must not depend on low-level modules — both should depend on abstractions. If A depends directly on the concrete class B, changes to B’s implementation can propagate to A; if A instead depends only on an abstraction (BSpec) that B implements, changes inside B are far less likely to affect A, as long as BSpec itself stays the same.
Even a small step towards this helps — programming against the List interface instead of the concrete ArrayList type means Student no longer depends on which list implementation the caller chose:
class Student {
private List<Course> courses; // not ArrayList<Course>
public Student(List<Course> courses) { this.courses = courses; }
public double calculateTotalGradePoints() { ... }
}What makes a good dependency? (stability and exposure)
A class A has a dependency on class B if A refers to B in code (an import B;, or, in the same package, simply referring to B anywhere). Not all dependencies are equally risky — two properties determine how good/bad one is:
- Stability — how likely the dependency is to change.
ArrayListis a good dependency because it’s very unlikely to change; treat classes you write as unstable until proven otherwise, and generally assume interfaces are more stable than concrete classes (unless they’re poorly designed and change often). - Exposure — how much of the depending class is entangled with it. A dependency only used in a constructor is better than one used across every method, since less of the class would need to change if that dependency changed.
Two forms of DIP
Minimising concrete dependencies (the simple form) — change a field’s compile-time type from a concrete class to whatever interface it already implements, wherever one already exists:
- HardwoodFloor placedOn;
+ Floor placedOn;This only helps where an abstraction already exists, though. The proper form of DIP goes further:
Remove dependencies on low-level components from high-level components — make both depend on an abstraction.
“High-level” vs “low-level” isn’t a strict distinction: high-level components implement application logic (e.g. a browser’s back/forward navigation history); low-level components do the grunt work that logic depends on (e.g. actually requesting a webpage’s data). The goal is for high-level components to talk to low-level ones exclusively through an abstraction, so a low-level component changing doesn’t force the high-level component depending on it to change too. Applied to a Desk class depending on a concrete LogitechKeyboard with no existing interface:
- Create an abstraction of the low-level component:
interface Keyboard { void type(char key); ... }. - Modify the low-level component to implement it:
class LogitechKeyboard implements Keyboard. - Minimise concrete dependencies in the high-level component:
Keyboard keyboard = new LogitechKeyboard();.
Dependency Injection
Dependency Injection (DI) is a design pattern that implements DIP by injecting a class’s dependencies into it (e.g. via the constructor) instead of having the class create them internally, promoting loose coupling (see java-cohesion-and-coupling):
// Before: AlertService is tightly coupled to EmailSender, and creates its own dependency.
class AlertService {
public void sendAlert(String msg) {
EmailSender sender = new EmailSender();
sender.send(msg);
}
}// After: AlertService depends on the MessageSender abstraction, injected via the constructor.
interface MessageSender {
void send(String msg);
}
class EmailSender implements MessageSender {
@Override
public void send(String msg) { System.out.println("Sending EMAIL: " + msg); }
}
class SmsSender implements MessageSender {
@Override
public void send(String msg) { System.out.println("Sending SMS: " + msg); }
}
class AlertService {
private MessageSender sender;
public AlertService(MessageSender sender) { this.sender = sender; }
public void sendAlert(String msg) { sender.send(msg); }
}AlertService can now send alerts via email, SMS, or any future MessageSender implementation, without ever changing its own code.
A constructor isn’t the only injection point — a setter is appropriate when the dependency is likely to change over the object’s lifetime, e.g. public changeSender(MessageSender sender) { this.sender = sender; }. Eventually something (typically an entry-point method like main) has to construct the concrete dependencies before injecting them; DI frameworks let you defer that construction to runtime via the framework’s own configuration instead of in code, but unless a project needs multiple levels of injected dependencies, good design alone can avoid the extra conceptual overhead of adopting one.
Summary
- Single Responsibility — one reason to change per class.
- Open-Closed — open for extension, closed for modification.
- Liskov Substitution — subclasses substitutable for their parents; no stronger preconditions, no weaker postconditions.
- Interface Segregation — many small, client-specific interfaces beat one large general-purpose interface.
- Dependency Inversion — depend on abstractions, not concretions; inject dependencies rather than constructing them internally.
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.
- begin with
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;
}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 13: 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) {…}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 ofvoidsupposed to imply in place? What about equal elements?square— over-general in one direction and over-specific in another: it namesMath.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 returnedListthe 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. Isfib(0)0 or 1? What happens for negativen, or for annwhose answer overflowslong?
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 14: 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.
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.
Version Control
A Week 4 supplementary topic, and the only one in the course that isn’t about Java. Not examinable (confirmed in 2026-05-28-course-summary-and-exam-preparation) — but it’s the piece of the course you’ll use every day afterwards.
Why
Software changes frequently, and version control preserves the history of those changes. The everyday shape of the thing is a word processor’s version-history sidebar: a list of edits, each entry timestamped and attributed to a named collaborator, with a Restore this version button.
The alternative most students reach for — copying files into another directory — is incredibly error prone. It ends up as a folder of Super Cool Report v1.xlsx … v3.1 … v4a … v4b … vFinal … vFinal_1 … vFinal_Final … vFinal_Final-UPDATED_NEW.xlsx, or a set of directories running project-v0.1 through project-v2.3 with a project-v2.1-backup wedged in the middle.
In real development we want three things that copying can’t give us:
- To work on our own version and send changes back (commit) when they work. We don’t want everyone editing the same code in real time; the software would rarely compile while others were working on it.
- Labelled changes — a record of what changed and why, so bad changes are easy to find and undo. Changes frequently introduce new bugs.
- To work with any text files, not just source.
What a VCS does
A version control system tracks a folder and its contents, the history of changes within it, and metadata about that history (when a change was made, and by whom). History is recorded as snapshots — the entire contents of the folder at one point in time.
Benefits in this course:
- Inspect old versions of your code — “this was working before!”
- Identify what you changed recently — and remember, be suspicious of recently changed code when debugging (see week5-lab-debugging).
- Practice for your future career.
Terminology
| Term | Meaning |
|---|---|
| Version control | Tracking the history of changes such that old versions can be restored |
| Repository | A folder placed under version control |
| Commit | A snapshot of a repository at a point in time |
| History | A list of commits in a repository |
By market share: Git 93.87%, Subversion 5.17%, none 4.31%, Mercurial 1.13%.
When to commit
Commit when you create something that works, or fix something that was broken.
| Commit | Do not commit |
|---|---|
Finished the dependencies method of addCustomer |
It’s 5 o’clock |
Fixed the code style of AddressBook |
Changing to a new computer |
Fixed a bug in Farm.core |
Completed the assignment |
Fixed a typo in the description of the update method |
The pattern: the left column describes a change to the code; the right column describes something that happened to you. A commit message should be about the former.
The staging area
To prepare a commit you add your changes to the staging area — the middle ground between what you have done to your files (the working directory) and what you last committed.
Figure 15: The three places a change can be, and the one command that moves it between each pair. This is the whole reason the staging area is a separate idea: git add does not save anything permanently and git commit does not look at your files, it looks at what you staged.
What should be committed?
Not everything in a folder belongs in version control. A repository should contain everything required to build or run the project, and not more.
- Beware generated files — if you don’t edit the file, don’t commit it.
- Beware proprietary formats like PowerPoint or Word documents — if your file is not plain text, consider leaving it out.
- Tell Git what to skip with a
.gitignore.
Common commands
| Command | Does |
|---|---|
git init |
Create a new Git repository |
git add |
Add working changes to the staging area |
git commit |
Commit the changes in the staging area |
git log |
View the repository history |
git diff |
View working changes |
Remotes — and a warning
A repository can be stored on a remote site; popular ones are GitHub, GitLab and BitBucket. An account with a lot of contributions can look good on a resume, but the rule that matters here is:
Do not make assessment public on these websites.
Publishing coursework counts as showing your code, which csse2002 lists explicitly under misconduct.
Further learning
Git is a powerful tool you’ll use extensively, and there is much more to it than the above. To go further, use the Git edX courses (accessible with a UQ student account) and the Atlassian Git tutorials.