|
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()
{
}
}
One Ping to “How to fix “Cannot make a static reference to the non-static method””
6 Responses to “How to fix “Cannot make a static reference to the non-static method””
-
Phuong Huynh Says:
May 6th, 2011 at 5:29 pmYour 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!
-
Manas Says:
June 14th, 2011 at 4:35 pmHi, thanks for your article, it was really very to the point, clear and helpful.
Keep posting.
-
ahmed albhy Says:
July 19th, 2011 at 1:03 amYour article is very good and easy to any one need information
-
ravi Says:
October 25th, 2011 at 5:25 amI read first line and it triggered what I did wrong. Thanks.
-
john jenever manga Says:
January 4th, 2012 at 7:49 pm.,thanks a lot you really helped me to understand the translation of static to non-static in java,.thanks.,.,^_^
-
john jenever Says:
January 9th, 2012 at 7:42 pm.,thanks a lot .,you really helped me,.,



September 30th, 2011 at 6:39 am
[...] 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… [...]