Dec 24

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()
   {
   }
} 

written by objects \\ tags: ,

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

  1. Android static vs nonstatic issue | Gravity Layouts Says:

    […] So I searched for that error and found this site: http://helpdesk.objects.com.au/java/how-to-fix-cannot-make-a-static-reference-to-the-non-static-meth… […]


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

  1. Phuong Huynh Says:

    Your article is very clean and neat, that’s what I need. I solved my problems at the first time I found it.

    Thank you very much!

  2. Manas Says:

    Hi, thanks for your article, it was really very to the point, clear and helpful.
    Keep posting. :-)

  3. ahmed albhy Says:

    Your article is very good and easy to any one need information

  4. ravi Says:

    I read first line and it triggered what I did wrong. Thanks.

  5. john jenever manga Says:

    .,thanks a lot you really helped me to understand the translation of static to non-static in java,.thanks.,.,^_^

  6. john jenever Says:

    .,thanks a lot .,you really helped me,.,

Leave a Reply

You must be logged in to post a comment.