Part 08 / Topic 4 of 12
Static versus instance members
An instance member (field or method) belongs to one object; writing this inside it refers to that object. A static member belongs to the class itself, shared by every object of that class — there is exactly one copy, however many objects exist, and this has no meaning inside a static method, which is why Stage 1 could call static methods without ever creating an object.
Think of the bank's "accounts opened today" counter on a branch notice board: it is one shared number for the whole branch, not something each customer carries a personal copy of.
Real-world example: every BankAccount shares one counter and one minimum-balance rule.
static class BankAccount {
private static int accountsOpened = 0; // one counter shared by every BankAccount
private static final double MIN_OPENING_BALANCE = 500.0; // one rule shared by every BankAccount
private final String accountNumber; // each object has its own
private double balance; // each object has its own
BankAccount(String accountNumber, double openingBalance) {
if (openingBalance < MIN_OPENING_BALANCE) {
throw new IllegalArgumentException(
"opening balance must be at least ₹" + MIN_OPENING_BALANCE + ", got ₹" + openingBalance);
}
this.accountNumber = accountNumber;
this.balance = openingBalance;
accountsOpened++; // changes the one shared counter
}
double balance() { return balance; }
static int accountsOpened() { return accountsOpened; } // no "this": does not belong to one object
}
accounts opened so far: 0
accounts opened so far: 2
rejected: opening balance must be at least ₹500.0, got ₹100.0
accounts opened so far: 2 (the rejected one did not count)
5000.0 and 750.0 stay separate per object
A good rule for choosing: if a value or rule is the same for every object of the class (a counter, a fixed fee, a shared cache), make it static. If it describes one particular object (a balance, a name), make it an instance member. Treat shared mutable static state as a smell: a static counter like accountsOpened that many constructors write to is still fine here because nothing reads it concurrently, but the same pattern becomes a real bug once two threads can increment it at once — the kind of hidden, hard-to-trace shared state that makes concurrency dangerous later in Stage 3.
Full program: examples/StaticVsInstance.java.
Done here? The practice set for Part 8 — including the solutions — is on the part page.