Compiler Error J0059

Cannot reference member 'identifier' without an object

The compiler detected an attempt to reference a variable without a known object association. This error usually occurs when an instance field or method (a field or method declared without the keyword static) is referenced from within a static method without a valid instance. Static methods cannot use instance fields and methods without a valid instance of the class.

The following example illustrates this error:

public class Simple {
   
   private int x;
   public void method1(){
      //Do something here
   }
   public static void main(String args[]) {
   
      x = 0; /* error: 'x' must be static or referenced using class
                instance */
      method1(); /* error: 'method1' must be static or referenced with
                           a class instance */
   }
}

The following example illustrates the correct method to refer to a non-static member field or method:

public class Simple{
   
   private int x; //access level of member does not matter
   public void method1(){
      //Do something here
   }
   public static void main(String args[]){
      //Create an instance of the 'Simple' class
      Simple smp = new Simple();
      smp.x = 0; //valid reference to field
      smp.method1(); //valid call to method
   }
}