Possible Duplicate:
What is the reason behind “non-static method cannot be referenced from a static context”?
Cannot make a static reference to the non-static method
cannot make a static reference to the non-static field
I am not able to understand what is wrong with my code.
class Two { public static void main(String[] args) { int x = 0; System.out.println("x = " + x); x = fxn(x); System.out.println("x = " + x); } int fxn(int y) { y = 5; return y; } }
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method fxn(int) from the type Two
i.e. referring a variable using static reference implies to referring using the class name. But, to access instance variables it is a must to create an object, these are not available in the memory, before instantiation. Therefore, you cannot make static reference to non-static fields(variables) in Java.
The obvious solution to fix "Cannot make a static reference to the non-static method or a non-static field" error in Java is to create an instance of the class and then access the non-static members. That's all for this topic Fix Cannot make a static Reference to The Non-static Method Error.
Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created.
You cannot refer non-static members from a static method. Non-Static members (like your fxn(int y)) can be called only from an instance of your class. or you can declare you method as static.
Since the main
method is static
and the fxn()
method is not, you can't call the method without first creating a Two
object. So either you change the method to:
public static int fxn(int y) { y = 5; return y; }
or change the code in main
to:
Two two = new Two(); x = two.fxn(x);
Read more on static
here in the Java Tutorials.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With