Skip to main content

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.

L1

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 static field is shared by all instances (and is usable with zero instances).
  • static methods can use other static members. They cannot use this, 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.
MemberPer instance?Can use this?
Instance field / methodYesYes
static field / methodNo (shared)No
static nested classN/ANo outer this
Inner (non-static) classTied to outer instanceYes (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.
L2

Advanced — Static Members

Class initialization and hiding

  • Class initialization is thread-safe: the JVM runs static initializers once under a lock.
  • A subclass static method with the same signature **hides** the parent method; it does not override. @Override on a static method is a compile error.
  • main is static so the JVM can start without constructing your class first (though initializing the class still runs static blocks).
  • Mutable static fields are shared global state — a source of test flakiness and race conditions.
L3

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.

L4

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);
    }
}
L5

Problem Solving Tricks

  • public static final constants use UPPER_SNAKE_CASE.
  • Keep static mutables private and synchronized or replace with AtomicInteger.
  • Unit tests should not depend on leftover static state — reset in @AfterEach or avoid the static.
  • Utility classes: private constructor + static methods (or just use a class with no instances).
L6

Practice Programs List

  1. Count how many objects of a class were created using a static field.
  2. Write static int gcd(int a, int b) and call it without creating an object.
  3. Add a static block that prints, then create two objects — confirm the block runs once.
  4. Try to use this in a static method and quote the error.
  5. Show static hiding: Parent and Child both have static void hello(), call via Parent and Child references.