Java error: non-static variable cannot be referenced from a static context
Codemia Knowledge Hub ·
This error means a static method (or other static context) is trying to use an instance variable or method directly. Instance members belong to a specific object, and a static method has no object to read them from. Fix it by making the member static, or by accessing it through an instance of the class.
Static vs non-static members
Java class members (variables and methods) are either static or non-static (instance):
- Static members belong to the class itself, not to any instance. You can use them without creating an object.
- Non-static members belong to instances. Each object has its own copy.
Because a non-static variable is tied to a particular object, accessing it requires a reference to that object. A static method belongs to the class as a whole and has no such reference.
Example that triggers the error
staticMethod has no instance of MyClass, so it cannot know which object's instanceVariable to read. The same applies to calling an instance method from main or any other static method.
Two ways to fix it
Either make instanceVariable static so staticMethod can read it directly, or pass in an instance and access the field through it:
Choosing between static and instance members
Use static members for constants and utility methods that do not depend on any object's state. A Celsius to Fahrenheit conversion method, for example, can be static because it needs no instance data. Use non-static members for state that varies from one object to another.
| Member Type | Owned By | Example Use Case | Access Method |
| Static | Class | Utility methods, constants | Directly through the class |
| Non-Static | Class Instance | Attributes/properties unique to instances | Through a class instance reference |
Related reading
- Normalization in DOM parsing with java - how does it work?
- NoSuchMethodError org.springframework.plugin.core.PluginRegistry.getPluginOrDefaultFor
- Null check in an enhanced for loop
- NullPointerException in Collectors.toMap with null entry values
- Non linear Regression Why isn't the model learning?
- None dimension raise ValueError in batch_norm with Tensorflow
- NullPointerException in Java with no StackTrace
- NullPointerException in Junit 5 MockBean
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.