Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot make a static reference to the non-static method fxn(int) from the type Two [duplicate]

Tags:

java

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

like image 288
kunal Avatar asked Jul 15 '12 12:07

kunal


People also ask

Can we make static reference to non-static method?

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.

How do you solve Cannot make a static reference to the non-static method?

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.

How do you solve error non-static variable this Cannot be referenced from a static context?

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.

How do you reference non-static?

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.


1 Answers

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.

like image 70
Keppil Avatar answered Sep 22 '22 17:09

Keppil