How to fix “Cannot make a static reference to the non-static method”

Java 19.6.2015 5 Comments

Static methods cannot call non-static methods. An instance of the class is required to call its methods and static methods are not accociated with an instance (they are class methods). To fix it you have a few choices depending on your exact needs.


/**
*  Will not compile
*/

public class StaticReferenceToNonStatic
{
   public static void myMethod()
   {
      // Cannot make a static reference
      // to the non-static method
      myNonStaticMethod(); 
   }

   public void myNonStaticMethod()
   {
   }
}

/**
* you can make your method non-static
*/

public class MyClass
{
   public void myMethod()
   {
      myNonStaticMethod(); 
   }

   public void myNonStaticMethod()
   {
   }
}

/**
*  you can provide an instance of the 
*  class to your static method for it 
*  to access methods from
*/

public class MyClass
{
   public static void myStaticMethod(MyClass o)
   {
      o.myNonStaticMethod(); 
   }

   public void myNonStaticMethod()
   {
   }
}

/**
*  you can make the method static
*/

public class MyClass
{
   public static void myMethod()
   {
      f(); 
   }

   public static void f()
   {
   }
} 

5 Responses to “How to fix “Cannot make a static reference to the non-static method””

  1. Sprofy

    Many Thanks, this helped me a lot.

  2. Alex

    Thank you for a very straightforward example regarding an issue that can be very perplexing to newbies.

  3. Passi

    Thanks, the second method helped me a lot.

  4. play_edu

    Thanks its Help a lot.

  5. Cj

    Thank you so much. Needed this for a class and the book was being no help.

Leave a Reply

s2Member®