Sub topic 4
What a static method can and cannot access
This chapter assumes you can write classes with fields, constructors, and methods, create objects with new, use public and private, and override methods in a subclass. It explains the rules for what code in a static context can reach, why those rules exist, and how to work around them correctly.
The core rule
A static method belongs to the class, not to any object. When the JVM calls it, no object is involved, so there is no this reference. Every restriction in this chapter follows from that one fact.
An instance field such as name really means "the name of some particular object". Inside a static method there is no particular object, so the compiler cannot tell which name you mean. It rejects the code instead of guessing.
| Code location | Has `this`? | Can use static members directly? | Can use instance members directly? |
|---|---|---|---|
| Instance method | Yes | Yes | Yes |
| Constructor | Yes | Yes | Yes |
| Static method | No | Yes | No |
| Static initializer block | No | Yes | No |
| Static field initializer | No | Yes | No |
What is allowed
Code in a static context can use:
- Static fields of the same class, by simple name.
- Other static methods of the same class, by simple name.
- Local variables and parameters declared inside the method.
- Instance members of any object it can get a reference to, such as a parameter, a local variable, or an object it creates, as long as it goes through that reference.
The first two are the common case. The Person class below reads the static field count directly.
public class Person {
private String name;
private static int count;
public Person(String name) {
this.name = name;
count++;
}
public static void printCount() {
System.out.println(count);
// System.out.println(name); // compile error: non-static field 'name' cannot be referenced from a static context
}
}The constructor is an instance context, so it can write both this.name and count. The static method printCount can read only count. The commented-out line fails with the error non-static variable name cannot be referenced from a static context. The exact wording depends on the compiler version.
What is not allowed
Inside a static method you cannot:
- Use
thisorsuper. - Read or write an instance field by its simple name.
- Call an instance method by its simple name.
- Refer to an instance inner class (a non-static nested class) without an enclosing object.
These are all compile-time errors. The program never starts, so you cannot hit them by accident at runtime.
The most common error: calling an instance method from `main`
Beginners meet this rule first in main, because main is static.
public class Greeter {
private String greeting = "Hello";
void sayHello() {
System.out.println(greeting);
}
public static void main(String[] args) {
// sayHello(); // compile error: non-static method sayHello() cannot be referenced from a static context
Greeter g = new Greeter();
g.sayHello();
}
}The fix is to create an object and call the method on it. The call g.sayHello() is legal in a static method because g supplies the missing object. The restriction applies to the simple name sayHello(), which would implicitly mean this.sayHello(). It does not apply to instance methods in general.
Reaching instance state through a reference
A static method can use instance members of a class, including private ones, if the code is inside that class and it has an object. Private access is checked per class, not per object.
public class Account {
private double balance;
public Account(double balance) {
this.balance = balance;
}
public static Account merge(Account a, Account b) {
return new Account(a.balance + b.balance);
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
Account total = merge(new Account(50), new Account(25));
System.out.println(total.getBalance());
}
}This prints 75.0. The static method merge reads a.balance and b.balance because it has explicit references. It does not need this.
Direction of access
The rule is asymmetric. An instance method can freely use static members, but a static method cannot freely use instance members.
The diagram below shows the same idea visually.
The reason is lifetime. Static members exist as soon as the class is initialized. Instance members exist only after an object is created. Code that exists earlier cannot assume that something created later is there. Code that runs on an object knows the class already exists.
A static method reading a static field
A static method that reads or writes static state is the typical pairing. In the next example, created is shared by all objects, and getCreated can read it with no object.
public class Counter {
private static int created = 0;
private final int id;
public Counter() {
created++;
id = created;
}
public int getId() {
return id;
}
public static int getCreated() {
return created;
}
public static void main(String[] args) {
new Counter();
Counter second = new Counter();
System.out.println(second.getId());
System.out.println(Counter.getCreated());
}
}The output is 2 then 2. The static field created has one copy. The instance field id has one copy per object. getId needs an object because it reads id. getCreated does not, because it reads only created.
Edge cases
Calling a static method through an object reference
Java lets you write obj.staticMethod(). The compiler resolves it using the declared type of obj and discards the object. The value of obj is never used.
public class NullCall {
static String hello() {
return "hello";
}
public static void main(String[] args) {
NullCall n = null;
System.out.println(n.hello());
}
}This prints hello and does not throw a NullPointerException. The code misleads readers, because it looks like an instance call. Write NullCall.hello() instead. Most IDEs and linters warn about the instance-style call.
Static field initializers cannot use instance state
A static field initializer runs in a static context. This does not compile:
public class Bad {
private int base = 10;
private static int doubled = base * 2; // compile error
}The reverse is fine. An instance field initializer may read a static field.
Forward references
Inside a class, a static initializer cannot read a static field by simple name before the field is declared. The compiler rejects this, because the field would still hold its default value.
public class Forward {
static int a = b + 1; // compile error: illegal forward reference
static int b = 5;
}Writing Forward.b instead of b bypasses the check. The code then compiles and a becomes 1, because b is still 0 when a is initialized. Avoid that trick, and declare fields in dependency order.
Local variables are always fine
A static method can declare ordinary local variables of any type, including objects of its own class. Locals live on the method's call stack and belong to that single call. They are not static state.
Generics and type parameters
A static member cannot use the type parameter of its generic class, because that parameter is tied to a particular instantiation, which is an object-level idea. A static method can declare its own type parameter instead.
import java.util.ArrayList;
import java.util.List;
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
// static T make(T v) would not compile: T is not available in a static context
public static <U> Box<U> of(U value) {
return new Box<>(value);
}
public static void main(String[] args) {
Box<String> b = Box.of("text");
System.out.println(b.value);
}
}The method declares its own <U>. This is why static factory methods on generic classes carry their own type parameter list.
Static methods and `main`
The entry point public static void main(String[] args) is static so the JVM can call it before any object exists. Anything main wants from the instance world, it must create first.
Working around the restriction
When a static method needs instance state, you have three honest options.
- Create an object inside the method and use it.
- Accept the object as a parameter, as
mergedoes. - Make the method an instance method, if it truly depends on one object's state.
Option 3 is often the right answer. If a method reads several instance fields, it probably belongs to the object. Making it static and passing everything in as parameters moves the problem without removing it.
A less honest workaround is to turn the instance field into a static one so that the static method compiles. This changes the meaning of the program. Every object now shares one value. Use it only when the data is genuinely shared by the whole class.
Summary of the rules
Exercise
The class below fails to compile. Name the line that causes the error, explain why, and give two different fixes that keep total as an instance field.
public class Cart {
private int total;
public void add(int amount) {
total += amount;
}
public static void reset() {
total = 0;
}
}
Show answer
The line total = 0; in reset causes the error. reset is static, so it has no this, and total is an instance field that belongs to a particular Cart. The compiler cannot tell which Cart's total is meant. Fix 1: make reset an instance method by removing static, so it runs on a specific Cart and total = 0 means this.total = 0. Fix 2: keep reset static but pass the object in, as in public static void reset(Cart c) { c.total = 0; }.
Exercise
In Forward, static int a = b + 1; static int b = 5; does not compile, but static int a = Forward.b + 1; does. What value does a hold after the class is initialized, and why?
Show answer
a holds 1. Static initializers run in textual order. When a is initialized, b has not been assigned yet, so it still has its default value 0. Using the qualified name Forward.b only avoids the compiler's forward-reference check. It does not change the order of execution.