The static and final Keywords
The manager wants to know how many orders Brew Bar has taken today. That number does not belong to any single order; it belongs to the café as a whole. And the rule "no more than 20 cups per order" should never change while the program runs. static and final express exactly these two ideas.
The rule
static belongs to the class; final can be assigned only once.
A static member has one copy shared by the whole class, instead of one per object:
public class Order {
public static final int MAX_CUPS = 20;
private static int ordersToday = 0;
private int cups;
public Order(int cups) {
if (cups > MAX_CUPS) {
throw new IllegalArgumentException("At most " + MAX_CUPS + " cups");
}
this.cups = cups;
ordersToday++;
}
public static int ordersToday() {
return ordersToday;
}
}Every new Order(...) has its own cups but increases the single shared ordersToday. You reach static members through the class name: Order.ordersToday(), Order.MAX_CUPS. main is static for the same reason: the JVM calls it before any object exists.
A static method has no "this object", so it cannot use instance fields or methods directly. cups inside ordersToday() would not compile: whose cups?
final means "assigned exactly once":
- A final variable cannot be reassigned.
static finalfields are constants, named in CAPITALS by convention. - A final method cannot be overridden by a subclass.
- A final class cannot be extended at all.
Stringis final.
One subtlety: final locks the variable, not the object it refers to. A final Drink house = new Drink("House", 250); can still have house.priceCents changed; you just cannot point house at another drink.
The shortcut
Ask of every field: "One per object, or one for everyone?" One for everyone → static. Then ask: "Should it ever change?" Never → final. Both answers together give a constant: static final.
cups
Each order has its own count, and it changes: an ordinary instance field.
Drills
Answer fast — trust the rule.
Starting from zero, the program runs new Order(2); new Order(5); new Order(1);. What is Order.ordersToday()?
What happens if ordersToday() (a static method) contains return cups;?
final Drink house = new Drink("House", 250); Which line compiles?
Why does class MyString extends String fail to compile?
Remember
- static belongs to the class; final can be assigned only once.
- Ask "one per object or one for everyone?" then "should it ever change?"
- Traps: using instance fields in a static method, and thinking final freezes the object.
