Compiler error message: Cannot make a static reference to the non-static field or method

By Alvin J. Alexander, devdaily.com

If you've ever seen a Java compiler error message like "Cannot make a static reference to the non-static method doFoo" or "Cannot make a static reference to the non-static field foo", here's a quick explanation of these messages.

I'll try to show the problem by example. In the source code below I've created an instance variable named foo and an instance method named doFoo. These are referred to as instance variables and methods because you must create an instance of the StaticReferenceExample class to instantiate and then use them. In other words, they aren't static fields of the class.

Hopefully that helps explain where these error messages come from. Because a static method, like the main method, exists at the class level (not the instance level), and can therefore be accessed without having an instance of the class created, the static method can't access and instance variable or method.

Here's an example Java class that intentionally creates both compiler errors. I've put comments by both statements that are not valid.

package com.devdaily.javasamples;

/**
 * Demonstrates invalid static references to an instance variables
 * and instance method.
 * Created by Alvin Alexander, http://devdaily.com.
 */
public class StaticReferenceExample
{

  // a sample instance variable
  private String foo = "foo";

  // a sample instance method  
  private void doFoo()
  {
  }
  
  // main is a static method
  public static void main(String[] args)
  {
    // creates this error: Cannot make a static reference to the non-static field foo
    foo = "bar";
    
    // creates this error: Cannot make a static reference to the non-static method doFoo
    doFoo();
  }
}

devdaily logo