8.3 Applying static to Methods & Fields

Key Takeaways

  • static fields and methods belong to the class itself rather than individual instances, with one shared copy of each static variable per loaded class.

  • A class static member selected through a reference expression does not require an instance. A null value alone causes no dereference, but evaluating the qualifier or arguments can throw.

  • A static context has no current instance. Use an object reference to access an instance member. The expressions this and super are forbidden in that context.

  • Ordinary static initializers and static blocks execute in textual order during class initialization. A blank static final field must be definitely assigned by the end of static initialization.

  • static methods cannot be abstract and are never overridden via runtime polymorphism—redeclaring a matching static method in a subclass hides the superclass method.

Last updated: November 2026

Applying static to Methods & Fields

The static keyword marks a class member as belonging to the class blueprint itself rather than to any single object created with new. Understanding what a static context can and cannot touch—and how the compiler resolves static calls—eliminates a large family of 1Z0-808 compilation and output traps.

Class-Level (static) vs. Instance Members

Each object has its own instance-field values. A static field is one variable for the declaring class, shared by its instances:

public class TicketCounter {
    public static int totalIssued = 0; // Shared by all instances
    public int localId;                // Separate per instance

    public TicketCounter() {
        totalIssued++;
        localId = totalIssued;
    }

    public static int getTotalIssued() {
        return totalIssued;
    }
}

If you create TicketCounter t1 = new TicketCounter(); and TicketCounter t2 = new TicketCounter();, then t1.localId is 1, t2.localId is 2, and TicketCounter.totalIssued is 2.

Three Ways to Invoke static Members (and the null Trap)

You can access a static field or method in three ways:

  1. Via the class name (recommended): TicketCounter.getTotalIssued()
  2. By simple name inside the same class: getTotalIssued()
  3. Via an instance reference (legal, discouraged, heavily tested): t1.getTotalIssued()

For a class static member, the compiler selects the declaration without using an object’s runtime class. A typed qualifier that evaluates to null does not itself cause NullPointerException:

// After constructing the two tickets shown above:
TicketCounter counter = null;
System.out.println(counter.totalIssued);      // Prints 2 (no NullPointerException!)
System.out.println(counter.getTotalIssued()); // Prints 2 (resolved via TicketCounter)
// System.out.println(counter.localId);       // Compiles, throws NullPointerException at runtime

Warning

When a question invokes ref.staticMethod() where ref is null, do not pick NullPointerException. The qualifier expression still evaluates and can have side effects or throw. When it completes normally, its value is discarded. Prefer the class name when you want no qualifier evaluation.

Strict static vs. Instance Context Rules

Instance methods have an implicit this reference pointing to the target object; static methods have no this and no super. Therefore, a strict boundary separates the two contexts:

From ContextAccess static Member?Access Instance Member Directly?Use this or super?
Instance method / constructor / {}Yes (directly)Yes (directly)Yes
static method / static {} blockYes (directly)No (compile error)No (compile error)

Attempting to touch an instance field or call an instance method directly inside main or any static method produces non-static variable/method ... cannot be referenced from a static context:

public class ContextDemo {
    private int instanceVal = 10;
    private static int classVal = 20;

    public void instanceWork() {
        System.out.println(instanceVal + classVal); // Both legal
    }

    public static void staticWork() {
        System.out.println(classVal);         // Legal
        // System.out.println(instanceVal);   // COMPILE ERROR: non-static variable instanceVal
        // instanceWork();                    // COMPILE ERROR: non-static method instanceWork()
        // System.out.println(this.classVal); // COMPILE ERROR: non-static variable this

        ContextDemo obj = new ContextDemo();  // Legal: explicit object reference
        System.out.println(obj.instanceVal);  // Prints 10
        obj.instanceWork();                   // Prints 30
    }
}

static Initializer Blocks & static final Constants

A static initializer block (static { ... }) executes exactly once when the JVM first initializes the class (before main runs if it is the entry class, or on first active use such as creating an instance or reading a nonconstant static field declared by that class). Ordinary static field initializers and static blocks execute in textual order. Static constant variables receive special initialization treatment. Reading a constant variable does not trigger initialization:

public class InitSequence {
    static int step = log("1: static field");

    static {
        System.out.println("2: static block");
    }

    { System.out.println("4: instance initializer"); }

    public InitSequence() {
        System.out.println("5: constructor");
    }

    static int log(String msg) {
        System.out.println(msg);
        return 1;
    }

    public static void main(String[] args) {
        System.out.println("3: main starts");
        new InitSequence();
    }
}

Running InitSequence prints 1: static field, 2: static block, 3: main starts, 4: instance initializer, 5: constructor. If a second new InitSequence() runs, steps 1 and 2 do not repeat—only steps 4 and 5 execute again.

A blank static final field must be definitely assigned by the declaring class’s static initialization and cannot be initialized by a constructor. A constant variable is a final primitive or String variable initialized with a constant expression. The declaration MAX_RETRIES below is a constant variable, while ENV is a blank final:

public class Constants {
    public static final int MAX_RETRIES = 3; // Assigned inline
    public static final String ENV;
    static {
        ENV = "PROD"; // Legal: assigned in static initializer
    }
    // public Constants() { ENV = "DEV"; } // COMPILE ERROR: cannot assign a value to final variable ENV
}

Note also that static final prevents reassigning the reference, not mutating a mutable object it points to: private static final StringBuilder LOG = new StringBuilder(); permits LOG.append("ok"), while LOG = new StringBuilder(); fails compilation.

static Methods Cannot Be abstract or Overridden

Because static methods resolve at compile time rather than by dynamic dispatch on an object's runtime class, two major OOP rules apply:

  1. static + abstract is illegal: An abstract method exists solely to be overridden polymorphically by a subclass, which contradicts static binding (illegal combination of modifiers: abstract and static).
  2. static methods are hidden, not overridden: A subclass declaration of a matching static method can hide an accessible superclass static method, subject to the signature, access, return, and throws requirements. Calling it via a Parent reference holding a Child instance invokes Parent's static method—unlike overridden instance methods! Moreover, you cannot hide a static parent method with an instance child method, nor override an instance parent method with a static child method; both fail compilation.
Test Your Knowledge

What happens when the following code is compiled and executed?

public class Counter {
    static int count = 5;
    int id = 1;
    static void ping() {
        System.out.print(count + ":");
    }
    public static void main(String[] args) {
        Counter c = null;
        c.ping();
        System.out.print(c.count);
    }
}
A

Compiles cleanly and throws NullPointerException on c.ping()

B

Compiles cleanly and prints 5:5

C

Compiles cleanly, prints 5:, and throws NullPointerException on c.count

D

Fails to compile because c is initialized to null

Test Your Knowledge

Which line inside class Config causes a compilation error?

public class Config {
    public static final int LIMIT;          // Line 1
    private static int active = 1;          // Line 2
    private int port = 8080;                // Line 3
    static {
        LIMIT = active * 10;                // Line 4
    }
    public Config() {
        port = active + 8000;               // Line 5
    }
    public static void show() {
        System.out.println(LIMIT + port);   // Line 6
    }
}
A

Line 1

B

Line 4

C

Line 6

D

Line 5

Test Your Knowledge

What is the output of running OrderTrace?

public class OrderTrace {
    static { System.out.print("A"); }
    { System.out.print("B"); }
    public OrderTrace() { System.out.print("C"); }
    static { System.out.print("D"); }
    public static void main(String[] args) {
        System.out.print("M");
        new OrderTrace();
        new OrderTrace();
    }
}
A

ADMBCBC

B

ABDCBC

C

ADMBMCBC

D

MADBCBC

Sections you finish are checked off in the contents.