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

Java FAQ: What does the Java error message “Cannot make a static reference to the non-static method/field” mean?

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.

Instance methods vs static methods

A short answer goes like this: In Java you have instance members (variables and methods) and static members:

  • Instance members belong to an instance of a class (what we call an object)
  • Static members can be accessed directly on the class (you don’t need an instance of a class to refer to static members)

Instance members are variables and methods that you can only access when you have an instance of a class. For example, if you create an instance of a String, like this:

String name = "Alvin";

name is an instance of a String (what we also call an object). The name instance has methods available to it like charAt, length, split, etc., and these are called instance methods. (Nobody uses the term “object methods,” but it may be helpful to think of them that way at this time. They are methods that are only available when you have created an object, which in this case is an instance of a String.)

As an important point, note that you don’t write code like this:

String.length();

That’s an attempt to call length as a static method. That doesn’t make sense, does it? length is a method in the String class (technically an “instance method”), and it’s only available when you have an instance of a String, such as name. (If you don’t have an instance of a String, it doesn’t make sense to call length.)

Now take a look at Java’s Math class. In this class, all of its methods are declared as static methods. A static method means that there is just one copy of that method, and you can call that method without having an instance of that class. For example, the abs method in the Math class is defined as a static method, so you can call it like this:

int value = Math.abs(-42);

That works, and the reason it works as shown is because abs is defined as static. Static means:

  • There is only one copy of this method (as opposed to one version of the method for every instance)
  • You can call abs without needing to first create an instance of Math

In fact, the way the Math class is written, this code doesn’t make much sense:

Math math = new Math();     // don't do this
int value = math.abs(-42);  // don't do this either

Because all of Math’s methods are static methods, it’s not intended to work this way.

To be clear, you don’t need an instance of the Math class to call its methods; because they are defined as static methods, you don’t need an instance of Math. Just call its methods directly, such as Math.abs(-42).

An example

If that doesn’t make sense, I’ll try to demonstrate more of this problem using an 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();
  }
}

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Permalink

so where is the solution

The solution is to access non-static fields and methods from non-static methods. In a small, sample Java class like this, you can access these methods from the class constructor, which is not a static method. Here's a modified version of that example Java class that shows how to get rid of those compiler errors. In this example, the main method creates a new instance of the class by calling the class constructor, and then the constructor can access the non-static members without generating the "cannot make a static reference to the non-static field or method" error message:

public class StaticReferenceExample
{

  private String foo = "foo";

  // a sample instance method  
  private void doFoo()
  {
    System.out.println("doFoo() was called");
  }

  // main is a static method
  public static void main(String[] args)
  {
    // create a new instance of our class
    new StaticReferenceExample();
  }

  // our constructor method is not static, so it can access
  // foo, and call doFoo() without creating an error.
  public StaticReferenceExample()
  {
    // the instance field can be accessed
    foo = "bar";
    // the  non-static method can be called
    doFoo();
  }
}
Permalink

IF below is my code:

public class duplicate {
int temp;
int ar[] = {'1', '2', '1', '7', '3'};
int count;
private void find() {
for(int i = 0; i < 4; i++) {
temp = ar[i];
if(ar[i] == ar[i+1] ) {
count += 1;
}

}
}

public static void main(String args[]) {
duplicate dup = new duplicate();
dup.find();

System.out.println("The No of duplicates is : " + count); //line 45

}

}
what do I need to remove the error
Cannot make a static reference to a non sttaic field sount at line 45

The thing you have to do here is make count a static field, because you're trying to reference it from a static method (main). Because a static method can be referenced by other classes without creating an instance of the class, you can't use an instance variable the way you have count shown.

Just put the static keyword before your declaration of count, and your code will work okay:

  // changed this to be static
  static int count;

Also, I'm not sure exactly what you're working on, but an incremental improvement to the code would be to return the count value from your find() method, something like this:

public class Duplicate
{
  int temp;
  int ar[] = { '1', '2', '1', '7', '3' };
  
  private int find()
  {
    int count = 0;
    for (int i = 0; i < 4; i++)
    {
      temp = ar[i];
      if (ar[i] == ar[i + 1])
      {
        count += 1;
      }
    }
    return count;
  }

  public static void main(String args[])
  {
    Duplicate dup = new Duplicate();
    int count = dup.find();

    System.out.println("The No of duplicates is : " + count); // line 45
  }

}
Permalink

It should be as this:

System.out.println("The No of duplicates is : " + dup.count); // line 45  

Sorry I am a DUMB

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.