Memra

Static vs instance: fields and methods

Class-level vs object-level members — when to use static and how to call each.

Two kinds of members

A static member belongs to the class — one copy, shared by all instances. An instance member belongs to each object — every instance has its own copy.

public class Counter {
    static int total = 0;   // shared across all Counters
    int count = 0;          // each Counter has its own

    void increment() {
        count++;
        total++;
    }

    static int getTotal() { return total; }
}

Counter a = new Counter();
Counter b = new Counter();
a.increment();
b.increment();
System.out.println(Counter.total); // 2 — prefer class-name syntax
System.out.println(a.count);       // 1

Key rules: - Static methods can only access static members directly — there is no this. - Instance methods can access both static and instance members. - Call static members via ClassName.member — calling via an object reference compiles but is misleading.

NORMAL ~/memra/learn/java-from-zero/static-vs-instance utf-8 LF