CSSE2002 — Week 2 Notes
Object Oriented Programming I
See csse2002 for staff, assessment, and course logistics.
Outline
- Objects, Classes, & Object-Oriented Programming
- Encapsulation
- Inheritance
- Abstraction
- Polymorphism (Week 3 — java-polymorphism)
Why OOP?
The case for objects rests on one running example grown in four stages: a bank, written first with nothing but static fields and static methods, then rewritten with objects. Watching what breaks at each stage is the argument for OOP. The bank carries only that argument. Inheritance has its own example, Employee, and abstraction another, PaymentProcessor/Payment. Polymorphism is left whole to Week 3.
Stage 1 — one global balance
public class BankBasic {
static double bankBalance = 0; // Single balance for the entire bank
public static void deposit(double amount) {
bankBalance += amount;
}
public static void withdraw(double amount) {
if (bankBalance >= amount) {
bankBalance -= amount;
} else {
System.out.println("Insufficient funds.");
}
}
public static void checkBalance() {
System.out.println("Bank Balance: $" + bankBalance);
}
public static void main(String[] args) {
deposit(5000);
withdraw(2000);
checkBalance(); // Output: Bank Balance: $3000.0
}
}The listing has two kinds of thing in it: the field bankBalance is a variable, x, and the three methods are functions of it, f(x). That framing — free variables on one side, free functions on the other — is the shape the next three stages keep running into.
There is one balance for the entire bank. There is no way to represent a second account, let alone a second customer.
Stage 2 — parallel arrays of accounts
public class BankWithAccounts {
static final int MAX_ACCOUNTS = 10;
static String[] accountNumbers = new String[MAX_ACCOUNTS];
static double[] balances = new double[MAX_ACCOUNTS];
static int accountCount = 0;
public static void createAccount(String accountNumber, double initialBalance) { ... }
public static int findAccountIndex(String accountNumber) { ... }
public static void deposit(String accountNumber, double amount) { ... }
public static void withdraw(String accountNumber, double amount) { ... }
public static void checkBalance(String accountNumber) { ... }
public static void main(String[] args) {
createAccount("A123", 1000);
createAccount("B456", 2000);
deposit("A123", 500);
withdraw("B456", 300);
checkBalance("A123"); // Expected: Balance for A123: $1500.0
checkBalance("B456"); // Expected: Balance for B456: $1700.0
}
}Every piece of account data needs its own array, and the arrays are held together only by agreeing on the index. accountCount has to be maintained by hand, and a findAccountIndex helper now stands between an account number and the position it names.
Stage 3 — parallel arrays of account holders too
public class BankWithHolders {
static final int MAX_ACCOUNTS = 10;
// Account Holder Data
static String[] holderIds = new String[MAX_ACCOUNTS];
static String[] holderNames = new String[MAX_ACCOUNTS];
static int holderCount = 0;
// Account Data
static String[] accountNumbers = new String[MAX_ACCOUNTS];
static double[] balances = new double[MAX_ACCOUNTS];
static String[] linkedHolderIds = new String[MAX_ACCOUNTS]; // Link accounts to holders
static int accountCount = 0;
public static void createAccountHolder(String id, String name) { ... }
public static int findHolderIndex(String holderId) { ... }
public static void createAccount(String accountNumber, double initialBalance,
String holderId) { ... }
public static int findAccountIndex(String accountNumber) { ... }
public static void deposit(String accountNumber, double amount) { ... }
public static void withdraw(String accountNumber, double amount) { ... }
public static void checkBalance(String accountNumber) { ... }
public static void main(String[] args) {
createAccountHolder("001", "Jack Johnson");
createAccountHolder("002", "Jill Smith");
createAccount("A123", 1000, "001");
createAccount("B456", 2000, "002");
deposit("A123", 500);
withdraw("B456", 300);
checkBalance("A123"); // Output: Balance for Jack Johnson: $1500.0
checkBalance("B456"); // Output: Balance for Jill Smith: $1700.0
}
}Adding a second kind of thing (holders) doubles the bookkeeping: two more parallel arrays, a second count, a second index-finder, and a third array (linkedHolderIds) whose only job is to remember which holder each account belongs to. Nothing in the language enforces that any of these arrays stay in step.
What that program actually looks like
Figure 1: The procedural picture after the three bank stages: every function and every variable lives in one flat frame, and any function may call any other. The boxes are functions, the ellipses are variables and the six arrows are calls.
The variables a, c and x belong to nobody. Any function may read or write any of them, and the call graph is free to cross in any direction. Nothing in the picture says which function is allowed to touch which variable — that knowledge lives only in the programmer’s head.
The fix: group each variable with the functions that act on it
Figure 2: Three self-contained units, each owning its own data and the functions that operate on it. Each unit has its own colour. This is a fresh illustration, not a literal regrouping of the procedural figure: f6 is new, f’ and f5 are gone, and f2 and f4 have different parameter lists.
This is the whole idea: instead of scattering related data across parallel arrays and free functions, bundle a variable and the functions that act on it into a single unit — a class. The second figure uses a fresh cast of functions, so don’t try to match the two figures member for member. Bundling the data and the functions that operate on the data into a single unit restricts direct access to some of an object’s components and can prevent the accidental modification of data.
Stage 4 — the same bank, with objects
The bank is then rewritten as four classes. Arrays do not disappear — each set of parallel arrays collapses into a single array of objects (BankAccount[], AccountHolder[]) held privately inside Bank, and the per-thing data that used to be spread across those arrays becomes fields on the object:
public class AccountHolder {
private String id;
private String name;
private String contactInfo;
public AccountHolder(String id, String name, String contactInfo) {
this.id = id;
this.name = name;
this.contactInfo = contactInfo;
}
public String getId() { return id; }
public String getName() { return name; }
public String getContactInfo() { return contactInfo; }
}
public class BankAccount {
private String accountNumber;
private double balance;
private AccountHolder accountHolder; // Association with AccountHolder
public BankAccount(String accountNumber, double initialBalance,
AccountHolder accountHolder) { ... }
public void deposit(double amount) { balance += amount; }
public void withdraw(double amount) { ... }
public double checkBalance() { return balance; }
public String getAccountNumber() { return accountNumber; }
public AccountHolder getAccountHolder() { return accountHolder; }
}
public class Bank {
private static final int MAX_ACCOUNTS = 10;
private BankAccount[] accounts = new BankAccount[MAX_ACCOUNTS];
private int accountCount = 0;
private AccountHolder[] accountHolders = new AccountHolder[MAX_ACCOUNTS];
private int holderCount = 0;
public void createAccountHolder(String id, String name, String contactInfo) { ... }
private AccountHolder findAccountHolder(String id) { ... }
public void createAccount(String accountNumber, double initialBalance,
String holderId) { ... }
private BankAccount findAccount(String accountNumber) { ... }
public void deposit(String accountNumber, double amount) { ... }
public void withdraw(String accountNumber, double amount) { ... }
public void checkBalance(String accountNumber) { ... }
public void displayAllAccounts() { ... }
}and the driver becomes a script against one bank object:
public class OOPBanking {
public static void main(String[] args) {
Bank bank = new Bank();
// Creating account holders
bank.createAccountHolder("001", "Jack Johnson", "jack@uq.com.au");
bank.createAccountHolder("002", "Jill Smith", "jill@uq.com.au");
// Creating accounts linked to account holders
bank.createAccount("A123", 1000, "001");
bank.createAccount("B456", 2000, "002");
// Performing transactions
bank.deposit("A123", 500);
bank.withdraw("B456", 300);
// Checking balances
bank.checkBalance("A123"); // Output: Balance for Jack Johnson: $1500.0
bank.checkBalance("B456"); // Output: Balance for Jill Smith: $1700.0
// Displaying all accounts
bank.displayAllAccounts();
}
}Three things changed, and they are the payoff:
- Every field is now
private— the arrays that used to bestaticand open to the world are hidden insideBank. findAccountHolderandfindAccountareprivate: index bookkeeping became an internal detail rather than part of the public surface.- The “which holder owns this account” link is a reference field on
BankAccount(private AccountHolder accountHolder), not a third parallel array. This kind of link is an association.
The four pillars of object orientation
- Encapsulation — see java-encapsulation
- Inheritance — see java-inheritance
- Abstraction — see java-abstraction
- Polymorphism — Week 3 (java-polymorphism, 2026-03-12-object-oriented-programming-ii)
The mechanics of each pillar
The mechanics under each pillar are written up in the concept notes:
| Topic | Note |
|---|---|
| classes vs objects, constructors and the default constructor | java-encapsulation |
access modifiers (private, public, protected, default) |
java-encapsulation |
| getters and setters | java-encapsulation |
the static keyword — class variables and static methods |
java-encapsulation |
| class invariants | java-encapsulation |
| method signatures and why they must be unique | java-encapsulation |
extends, super, method overriding |
java-inheritance |
| interfaces and abstract classes | java-abstraction |
Two items are homework:
protectedaccess — read DigitalOcean’s Java access modifiers tutorial.- Interface vs abstract class — two Stack Overflow threads to read; picked up in 2026-03-12-object-oriented-programming-ii.
Preconditions and postconditions come in Week 3 — see java-specification.
Java Basics Practical - Palindromes
Practical exercises for week 2. IntelliJ IDEA is the course’s supported IDE (see the install guide on Blackboard). The Java 21 API docs cover the String class in java.lang, which is needed below.
On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "true"), 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).
Question 1 — Palindromes
A palindrome reads the same forwards and backwards, e.g. "AaaA", "madamimadam", "racecar".
Implement four methods, all with the signature public static boolean isPalindromeN(String word) (for \(N=1..4\)), each using a different technique:
isPalindrome1— aforloop.isPalindrome2— awhileloop.isPalindrome3— recursive, with no helper methods.isPalindrome4— recursive, using a private helper method.
All four should agree on at least these cases. What does each return?
isPalindromeN("AaA") →
isPalindromeN("A") →
isPalindromeN("") →
isPalindromeN("Abbb") →
All four methods do the same comparisons — first character against last, second against second-last, and so on — but they keep track of where they are up to in two structurally different ways:
Figure 3: The two reductions behind the four methods. (a) isPalindrome1, isPalindrome2 and isPalindrome4 leave the string alone and move an index i inwards, comparing charAt(i) with charAt(len - i - 1) and stopping once i reaches len / 2 - which is why the middle character of an odd-length word is never examined. (b) isPalindrome3 keeps no index at all: it compares the two ends, then recurses on substring(1, length() - 1), so the string itself shrinks by two characters per call until length() < 2 is the base case. Characters no longer in the live window are greyed out; the teal double arrows are comparisons.
Task 0 — isPalindrome1 (for loop):
public static boolean isPalindrome1(String word) {
int len = word.length();
for (int i = 0; i < len / 2; i++) {
if (word.charAt(i) != word.charAt(len - i - 1)) {
return false;
}
}
return true;
}Task 1 — isPalindrome2 (while loop):
public static boolean isPalindrome2(String word) {
int len = word.length();
int i = 0;
while (i < len / 2) {
if (word.charAt(i) != word.charAt(len - i - 1)) {
return false;
}
i++;
}
return true;
}Task 2 — isPalindrome3 (recursive, no helper methods). To write any recursive method, identify the base case (the input is trivially solvable — obviously a palindrome or obviously not) and the recursive case (which must reduce the problem to a smaller one, moving towards the base case). Applied here: if \(xy \ldots yx\) is a palindrome, then \(y \ldots y\) must be too — and substring is how you extract \(y \ldots y\) (panel (b) of Figure 3).
public static boolean isPalindrome3(String word) {
if (word.length() < 2) {
return true; // base case
}
if (word.charAt(0) != word.charAt(word.length() - 1)) {
return false; // base case
}
return isPalindrome3(word.substring(1, word.length() - 1)); // recursive step
}Task 3 — isPalindrome4 (recursive, with a private helper). The helper carries the index, so this is panel (a)’s reduction driven by recursion rather than by a loop. Because the index does the work, this version never calls substring, so unlike isPalindrome3 it allocates no new String on each step.
public static boolean isPalindrome4(String word) {
return helper(word, 0);
}
private static boolean helper(String word, int i) {
if (i >= word.length() / 2) {
return true; // base case
}
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
return false; // base case
}
return helper(word, i + 1); // recursive step
}All four agree on the required test cases: "AaA" → true, "A" → true, "" → true, "Abbb" → false.
Code review
A paired activity, not a gradable exercise: swap solutions with a partner, and for each other’s code —
- Understand it, and ask questions about anything unclear.
- Check correctness against the test cases above (and a few of your own).
- Check it follows the course style guide.
- Discuss/suggest improvements if you find issues.
Then discuss which of the four isPalindromeN techniques you each preferred, and why.
Java Basics Applied Class
Applied class exercises for week 2, reviewing week 1’s 2026-02-26-course-overview-and-java-basics content (switch statements, arrays, recursion). Meant to be done without a computer — you’re welcome to look up Java/library information, but your group knowing the answer isn’t a substitute for individual competence.
On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "46368"), 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).
Question 1 — Numbers to Numbers
Implement a method, nameOf, with the signature public static String nameOf(int value). If 0 < value < 10, return the name of the number, otherwise return "??".
What does each call return?
nameOf(4) →
nameOf(7) →
nameOf(24) →
Task 0 — using switch:
public static String nameOf(int value) {
return switch (value) {
case 1 -> "One";
case 2 -> "Two";
case 3 -> "Three";
case 4 -> "Four";
case 5 -> "Five";
case 6 -> "Six";
case 7 -> "Seven";
case 8 -> "Eight";
case 9 -> "Nine";
default -> "??";
};
}The modern -> switch expression syntax is preferred over a traditional switch statement because it avoids one case accidentally falling through into the next if a break is omitted.
The traditional statement form, for comparison, needs a result variable and a break in every arm:
public static String nameOf(int value) {
String result;
switch (value) {
case 1:
result = "One";
break;
...
default:
result = "??";
}
return result;
}Task 1 — using an array of strings. The array is indexed from 0 but the names start at 1, hence the value - 1:
public static String nameOf(int value) {
String[] numbers = {"One", "Two", ... };
String result = "??";
if (value > 0 && value < 10) {
result = numbers[value - 1];
}
return result;
}An equivalent early exit version deals with the exceptional case first, so the rest of the method is just the primary behaviour:
public static String nameOf(int value) {
if (value <= 0 || value >= 10) {
return "??";
}
String[] numbers = {"One", "Two", ... };
return numbers[value - 1];
}Bonus — extending to 10-99, using tiered helpers. Each helper is narrow enough to be a plain array lookup, and carries its own precondition as a Requires: Javadoc comment (the course’s specification style — see java-specification) rather than checking it at runtime; nameOf is then just the dispatcher that guarantees those preconditions hold:
/** Requires: value > 0 && value < 10 **/
private static String ones(int value) {
String[] numbers = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
return numbers[value - 1];
}
/** Requires: value >= 10 && value < 20 **/
private static String teens(int value) {
String[] numbers = {"Ten", "Eleven", /* ... */};
return numbers[value - 10];
}
/** Requires: value >= 20 && value < 100 **/
private static String tens(int value) {
String[] numbers = {"Twenty", "Thirty", /* ... */};
return numbers[value / 10 - 2];
}
public static String nameOf(int value) {
if (value > 0 && value < 10) {
return ones(value);
}
if (value >= 10 && value < 20) {
return teens(value);
}
if (value >= 20 && value < 100) {
if (value % 10 == 0) {
return tens(value);
} else {
return tens(value) + " " + ones(value % 10);
}
}
return "??";
}Question 2 — Fibonacci Sequence
The Fibonacci sequence (\(0, 1, 1, 2, 3, \ldots\)) is defined as \(\mathcal{F}(0)=0\), \(\mathcal{F}(1)=1\), \(\mathcal{F}(n) = \mathcal{F}(n-1) + \mathcal{F}(n-2)\) for \(n \geq 2\): 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Implement public static int fib(int n), returning the \(n\)th element — so fib(1) → 1 and fib(2) → 1. What is fib(24)?
public static int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib(n - 2);
}fib(24) → 46368.
Desk check. A desk check is a manual (non-computerised) technique for checking the logic of an algorithm: the person performing the check effectively acts as the computer, using pen and paper to record results.
The desk check of fib(6) below is a graph with one node per distinct call rather than a full call tree, and one arrow per return:
Figure 4: A desk check of fib(6). Each node is one distinct call F(k); each arrow runs from a callee back to its caller and is labelled with the value that call returned, so a node’s own value is the sum of the two labels entering it (F(6) receives 5 from F(5) and 3 from F(4), giving 8). Repeated calls are collapsed: fib’s recursion really evaluates F(4) twice, F(3) three times and so on, but only one node per k is drawn, so what is pictured is the dependency DAG rather than the call tree.
Reading Figure 4 bottom-right to top-left is exactly the order the recursion unwinds: the base cases F(1) = 1 and F(0) = 0 return first, and every other node adds the two labels arriving at it. That is also the reason this implementation is slow — the picture hides the fact that the collapsed nodes are recomputed from scratch on every visit.
Question 3 — The Collatz Conjecture
Start with any positive integer \(n\): if even, divide by 2; if odd, multiply by 3 and add 1; repeat. The (unproven, but checked below \(2075 \times 2^{60}\) as of 2025) conjecture is that this always reaches 1.
Implement public static int collatz(int n), returning the number of steps to reach 1 — so collatz(1) → 0, since 1 is already there. Sketch the process before writing any code; a flow chart is a good start. What is collatz(3)?
The process the method has to run is a single loop with a two-way test inside it:
Figure 5: The Collatz step as a flow chart, in the ordinary flow-chart conventions (rounded terminator, rectangle for a process step, diamond for a decision). Every box corresponds to exactly one line of the solution: the counter increments once per iteration, after the branch and before the test is re-evaluated, which is why collatz(1) is 0 and not 1.
Transcribing Figure 5 gives the solution directly:
public static int collatz(int n) {
int steps = 0;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
steps++;
}
return steps;
}Trace for collatz(3): 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1, which is 7 steps.
Worked examples:
| call | result |
|---|---|
collatz(1) |
0 |
collatz(2) |
1 |
collatz(3) |
7 |
collatz(4) |
2 |
Question 4 — Ackermann function (extra)
The Ackermann–Péter function: \(\mathcal{A}(m,n) = n+1\) if \(m=0\); \(\mathcal{A}(m-1, 1)\) if \(m>0, n=0\); \(\mathcal{A}(m-1, \mathcal{A}(m, n-1))\) if \(m>0, n>0\).
Implement public long ackermann(short m, short n), and explain why it takes short parameters but returns a long.
The direct transcription of the three cases has one if per line of the definition:
public long ackermann(short m, short n) {
if (m == 0) {
return n + 1;
}
if (m > 0 && n == 0) {
return ackermann(m - 1, 1);
}
if (m > 0 && n > 0) {
return ackermann(m - 1, ackermann(m, n - 1));
}
}This does not actually compile, because of Java’s implicit type promotion (see java-casting, covered later in the course): arithmetic on short operands (m - 1, n - 1) promotes them to int, which is not assignable back to a short parameter. The compiling version adds an explicit (short) cast at every recursive call, plus a final return so that every path returns a value:
public long ackermann(short m, short n) {
if (m == 0) {
return n + 1;
}
if (m > 0 && n == 0) {
return ackermann((short) (m - 1), (short) 1);
}
if (m > 0 && n > 0) {
return ackermann((short) (m - 1),
(short) ackermann(m, (short) (n - 1)));
}
return -1; // Impossible case but required for coverage.
}Why short in, long out? The Ackermann function grows extremely rapidly even for small inputs, so the parameters are restricted to short (deliberately small inputs) while the result is a long, so the (much larger) output can be represented without overflow.
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 6: 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
abstractkeyword 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
Animalabstract class shared byDogandCat. 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, SwimmableBoth 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 7: 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 8: 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 8. 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 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 9: 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 10: 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:
- Must be established after the class constructor.
- May be assumed as a precondition of each method (excluding the constructor).
- Must be established after each method call.
class Counter {
private int count;
public Counter() { count = 0; }
public void increment() { count = count + 1; }
}
// Invariant: count >= 0Trace 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:
- Public fields — a directly-mutable field lets any caller bypass the class entirely and violate the invariant. Fix: make the field
private. - 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 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 11: 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 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 12: 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 12 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.
- 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.