Java OOP
Static Members
Complete lesson for Static Members using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Static Members
Section: Java OOP. static fields, methods, blocks, and static nested classes — class-level data without this.
static means “belongs to the class”
- One
staticfield is shared by all instances (and is usable with zero instances). staticmethods can use other static members. They cannot usethis,super, or instance fields unless they have an object reference.- Call as
ClassName.method()— calling via an instance works but is misleading.
public class IdFactory {
private static int nextId = 1;
private final int id;
IdFactory() {
id = nextId++;
}
static int peekNext() {
return nextId;
}
public static void main(String[] args) {
IdFactory a = new IdFactory();
IdFactory b = new IdFactory();
System.out.println(a.id + "," + b.id);
System.out.println("next=" + IdFactory.peekNext());
}
} static block and initialization order
static { }runs once when the class is initialized (first active use). Used for complex static setup.- Order: static fields and static blocks in source order, then (per
new) instance fields/blocks, then constructor.
| Member | Per instance? | Can use this? |
|---|---|---|
| Instance field / method | Yes | Yes |
static field / method | No (shared) | No |
static nested class | N/A | No outer this |
| Inner (non-static) class | Tied to outer instance | Yes (Outer.this) |
When static is the right tool
- Pure functions (
Math.max), factories (List.of), constants (public static final). - Not a dumping ground for “I did not want to pass an object”. That is a global variable in disguise.
Advanced — Static Members
Class initialization and hiding
- Class initialization is thread-safe: the JVM runs static initializers once under a lock.
- A subclass
staticmethod with the same signature **hides** the parent method; it does not override.@Overrideon a static method is a compile error. mainis static so the JVM can start without constructing your class first (though initializing the class still runs static blocks).- Mutable
staticfields are shared global state — a source of test flakiness and race conditions.
Tricky Interview Points
Q1) Can a static method use instance variables?
Answer Not directly. It has no this. It can use them only via an object reference passed in or created inside.
Q2) When does a static block run?
Answer Once, when the class is initialized — typically at first use (new, static method, static field access).
Q3) static vs instance field?
Answer static is shared across objects. Instance fields are unique per object.
Q4) Can we override a static method?
Answer No. You can hide it with the same signature in a subclass. Dispatch is compile-time based on the reference type.
Q5) Why is main static?
Answer The launcher has no instance. public static void main lets it invoke the method by class name.
Q6) What is a static nested class?
Answer A nested class that does not hold a hidden reference to an outer instance. Prefer it when the nested type does not need outer state.
Simple Programs
Static block and shared counter
public class StaticBlockDemo {
static final String APP;
static {
APP = "LearnCodeGuru";
System.out.println("class ready");
}
static int count;
StaticBlockDemo() {
count++;
}
public static void main(String[] args) {
new StaticBlockDemo();
new StaticBlockDemo();
System.out.println(APP + " count=" + count);
}
} Problem Solving Tricks
public static finalconstants useUPPER_SNAKE_CASE.- Keep static mutables
privateand synchronized or replace withAtomicInteger. - Unit tests should not depend on leftover static state — reset in
@AfterEachor avoid the static. - Utility classes:
privateconstructor + static methods (or just use a class with no instances).
Practice Programs List
- Count how many objects of a class were created using a static field.
- Write
static int gcd(int a, int b)and call it without creating an object. - Add a static block that prints, then create two objects — confirm the block runs once.
- Try to use
thisin a static method and quote the error. - Show static hiding: Parent and Child both have
static void hello(), call via Parent and Child references.