Add to Google Reader or Homepage

Non-static method cannot be referenced by static context

Accessing Non-Static method from Static method:

In java there is a limitation that the static method can only be accessed by the another static method and also that a non-static method cannot be accessed from static context.

So whenever a statement in the main() function tries to access the non static method this error would be thrown,since the main function is a static function.

This type of errors can be eliminated by converting the non-static function in to a static function or vice-versa.

we cannot be able to convert a main() function into a non-static function.So the only way possible to deal with this error is trying to convert the non-static function into a static function.

Note that this error is not limited to the main() function and it applies to all the functions that you use in your program.So remember that whenever you are trying to access a static function or a static field,ensure that the caller location is inside a static funtion.

Look at the following example program to understand the context when this kind of error would occur. 


public class Nullpointer
public static void main(String args[])
String name=null;

public void check(String s)
System.out.println("granted access");


C:\blog\ non-static method check(java.lang.String) cannot be
referenced from a static context
1 error

In the above program i have a class Nullpointer within which i have declared a function check() which is a non-static function.

Since,i have tried to access the check() function from the main() this error is shown when compiling the program.
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top