Skip to the workspace
Pebellslearn by building
Classes and Objects  ›  Capstone Project

The static and final Keywords

Static Keyword 14 minA static member is shared by the whole class rather than copied into each object, and final means a variable is assigned once, a method cannot be overridden and a class cannot be extended.

java / The static and final Keywords

Explore each scene at your own pace.

01 · The rule

The rule

The static and final Keywords

A static member is shared by the whole class rather than copied into each object, and final means a variable is assigned once, a method cannot be overridden and a class cannot be extended.

Separate class-level members from instance members and reassignment restrictions.

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 final fields are constants, named in CAPITALS by convention.
  • A final method cannot be overridden by a subclass.
  • A final class cannot be extended at all. String is 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.