Discussion Threads
1
One copy for the class, or one copy per object?
Static vs Instance Members
💾 Live Memory Visualizer
Metaspace (Class Data)
static int studentCount = 0
ONE copy — shared by all 0 objects
Heap (Instance Data) — 0 objects
No objects yet — click "+ new Student()"
⊞
Static vs Instance Members
A static (class) member belongs to the class itself — there is exactly one copy, shared by all instances. An instance member belongs to each individual object — every new object gets its own copy. Static fields live in JVM Metaspace (loaded once when the class loads), while instance fields live on the Heap (allocated each time you call "new"). The static keyword marks a member as class-level. A common use case is a counter that tracks how many objects have been created — the counter is static (shared), while each object's name or ID is an instance field (unique per object).
Key Ideas
1static = one copy shared by ALL instances (class-level)
2Instance = one copy PER object (object-level)
3Static fields live in Metaspace; instance fields live on the Heap
4Access static members via ClassName.member (preferred) or instance.member
5Common uses: counters, constants (static final), utility methods
Strengths
- ✦Static fields save memory — one copy instead of N copies
- ✦Static methods callable without creating an object (e.g., Math.sqrt())
- ✦static final creates true constants shared across the program
Weaknesses
- △Mutable static fields create shared state — thread-safety risk
- △Static methods cannot be overridden (only hidden)
- △Overuse of static leads to procedural code, not OOP
Used in:Math.PI (static final), Integer.parseInt() (static method), object counters, configuration constants
Static vs Instance Members Quiz
Static vs Instance Members Quiz
QUIZ 1/6class Counter {
static int count = 0;
Counter() { count++; }
}
Counter a = new Counter();
Counter b = new Counter();
Counter c = new Counter();
System.out.println(a.count + " " + Counter.count);What is the output?
Practice Exercises
Classify each characteristic: Does it describe a Static member or an Instance member?
EXERCISE 1/3One copy shared by all objects
Each object gets its own copy
Accessed via ClassName.member
Accessed via object reference
Lives in Metaspace (Method Area)
Lives on the Heap
Cannot use "this" keyword
Has implicit "this" reference
Static Member
Instance Member
Match each access modifier to its visibility scope.
EXERCISE 2/3Accessible everywhere
Same package + subclasses
Same package only
Same class only
public
protected
default
private
Sort each getter/setter benefit into the correct category.
EXERCISE 3/3Validate input before accepting
Make a field read-only (getter only)
Make a field write-only (setter only)
Change internal representation without breaking callers
Any value can be assigned without checks
External code depends on field type directly
Getter/Setter Advantage
Public Field Problem