3 · Object-Oriented Core · lesson 14 of 41

this, static & final

Instance vs class members, and immutability.

Java
public class Counter {
    private static int total = 0;   // shared across all instances
    private final int id;           // set once per instance
    private int hits;

    public Counter() {
        this.id = ++total;
    }
    public static int totalCreated() { return total; }
}
  • ▸static members belong to the class, not any instance.
  • ▸final variables can be assigned only once.
  • ▸this refers to the current instance.
Key takeaways
  • ✓static = one copy per class.
  • ✓final = write-once.