May 7, 2022

Cannot Make a Static Reference to The Non-static Method or Field

This post shows what does "Cannot make a static reference to the non-static method or a non-static field" error means and how to fix that error.

static reference to the non-static field or method error

In order to understand why this error crops up you’ll have to understand the difference between instance member (field and method) and class members.

  1. Instance members- These members i.e. instance fields and instance methods belong to an instance (object) of a class. You can invoke instance methods and access instance variables only through an object of the class and each object of the class has its own separate copy of the instance members.
  2. Class members (Static members)- Static members of the class are associated with the class which means separate copies of fields and methods declared as static won’t be created for every object of the class. You can access only static members from a static context.

So you see the problem here? You can access a static method with out even creating any object of the class but trying to access a non-static method from that static method poses the dilemma; to which instance does that non-static method belong to, any instance of the class is even created or not. That’s why you get this error "Cannot make a static reference to the non-static method or a non-static field".

For example consider the following class where we are trying to invoke a non-static method instanceMethod() from the static main method and also trying to access non-static field i.

public class StaticDemo {
  int i = 0;
  public static void main(String[] args) {
    System.out.println("in main method which is static");
    // Trying to access non-static field
    i = 5;
    // Trying to access non-static method
    instanceMethod();
  }

  public void instanceMethod(){
    System.out.println("Value of i- " + i);
  }
}

Code gives compile-time error for both of the non-static members.

Cannot make a static reference to the non-static field i
Cannot make a static reference to the non-static method instanceMethod()

Fixing static reference to the non-static method or field error

As you must be knowing by now you need an object to access instance members of the class so create an object and use that to access non-static fields.

public class StaticDemo {
  int i = 0;
  public static void main(String[] args) {
    System.out.println("in main method which is static");
    StaticDemo obj = new StaticDemo();
    obj.i = 5;
    obj.instanceMethod();
  }

  public void instanceMethod(){
    System.out.println("Value of i- " + i);
  }
}
Output
in main method which is static
Value of i- 5

That's all for the topic Cannot Make a Static Reference to The Non-static Method or Field. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment