Java
Programming Errors
Static Variables
Non-static Variables
Coding Concepts

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

java
1public class MyClass {
2    int instanceVariable = 10; // Non-static variable
3
4    public static void staticMethod() {
5        System.out.println(instanceVariable); // Error
6    }
7}

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:

java
1public class MyClass {
2    int instanceVariable = 10;
3
4    public static void staticMethod(MyClass obj) {
5        System.out.println(obj.instanceVariable); // Correct
6    }
7}

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 TypeOwned ByExample Use CaseAccess Method
StaticClassUtility methods, constantsDirectly through the class
Non-StaticClass InstanceAttributes/properties unique to instancesThrough a class instance reference

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data 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.

Practice algorithms