Interview Q&A · Java · 4 questions in this topic
Static Members: Variables, Methods & Access Rules — Java Interview Q&A
Static members belong to the class, not to any instance. That single fact explains every rule about them — including why static methods cannot touch instance state. Part of Methods & Constructors · 294 questions in the Java bank.
What are static blocks and static initialisers?
Answer
A static block (static { ... }) is initialisation code that runs exactly once, when the class is first loaded and initialised — before any constructor or main() runs, and in the textual order the blocks appear. It is the place for static-field setup too complex for a one-line assignment. The sibling concept, an instance initialiser block ({ ... }), runs once per object, before each constructor body.
Example
class Config { static final Map<String, String> DEFAULTS = new HashMap<>(); static { DEFAULTS.put("mode", "prod"); // runs once, at class-load time } }
Can static methods access instance variables?
Answer
No — not directly. A static method runs without any object, so there is no this and no instance state to read. Attempting it fails compilation with "non-static variable cannot be referenced from a static context". A static method can still use instance state if you hand it an object explicitly and qualify the access (obj.field).
Example
class A { int x = 1; static void f(A a) { System.out.println(a.x); } // legal: via a reference // static void g() { System.out.println(x); } // illegal }
How do we access static members?
Answer
Through the class name — ClassName.member — which signals that no instance is involved. Java also permits access through an object reference (obj.member), but compilers warn against it because it misleadingly suggests instance state. Static imports (import static ...) let you use static members unqualified.
Example
Math.max(3, 7); // class-name access (preferred) import static java.lang.Math.max; max(3, 7); // static-import access
Can static methods be overridden?
Answer
No. Static methods belong to the class, and overriding is an instance-level, runtime mechanism. If a subclass declares a static method with the same signature, it hides the superclass version rather than overriding it — which version runs depends on the reference type at compile time, not the object type at runtime. The @Override annotation is rejected on a static method, which is the quickest way to prove it.
Example
class A { static void f() { System.out.println("A"); } } class B extends A { static void f() { System.out.println("B"); } } A x = new B(); x.f(); // prints "A" — resolved by reference type, i.e. hiding, not overriding
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission