[java] non static method cannot be referenced from a static context

First some code:

import java.util.*;
//...

class TicTacToe 
{
//...

public static void main (String[]arg) 
{ 

    Random Random = new Random() ; 
    toerunner () ; // this leads to a path of 
                   // methods that eventualy gets us to the rest of the code 
} 
//... 

public void CompTurn (int type, boolean debug) 
{ 
//...

        boolean done = true ; 
        int a = 0 ; 
        while (!done) 
        { 
            a = Random.nextInt(10) ;
            if (debug) { int i = 0 ; while (i<20) { System.out.print (a+", ") ; i++; }} 
            if (possibles[a]==1) done = true ; 
        } 
        this.board[a] = 2 ; 


}
//...

} //to close the class 

Here is the error message:

TicTacToe.java:85: non-static method nextInt(int) cannot be referenced from a static context
            a = Random.nextInt(10) ;
                      ^

What exactly went wrong? What does that error message "non static method cannot be referenced from a static context" mean?

This question is related to java static

The answer is


In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.

Here's something you might want to do:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.


Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.

The variable Random is only "in scope" inside the main method. It's not accessible to any methods called by main. When you return from main, the variable disappears (it's part of the stack frame).

If you want all of the methods of your class to use the same Random instance, declare a member variable:

class MyObj {
  private final Random random = new Random();
  public void compTurn() {
    while (true) {
      int a = random.nextInt(10);
      if (possibles[a] == 1) 
        break;
    }
  }
}

You're trying to invoke an instance method on the class it self.

You should do:

    Random rand = new Random();
    int a = 0 ; 
    while (!done) { 
        int a = rand.nextInt(10) ; 
    ....

Instead

As I told you here stackoverflow.com/questions/2694470/whats-wrong...