It is not possible to make a static reference to the non-static fxn (int) method of type Two

Possible duplicate:
What is the reason for the "non-static method cannot be referenced from a static context"?


Unable to make a static reference to a non-static method
cannot statically refer to non-static fields

I can not 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: It is not possible to make a static reference to the non-static method fxn (int) from type Two

+4
source share
4 answers

Since the main method is static and the fxn() method is not, you cannot invoke the method without first creating the Two object. Therefore, 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); 

More on static here in the Java Tutorials .

+19
source

You cannot access the fxn method as it is not static. Static methods can directly access other static methods. If you want to use fxn in your main method, you need to:

 ... Two two = new Two(); x = two.fxn(x) ... 

That is, create two objects and call a method for this object.

... or make the fxn method static.

+3
source

You cannot reference non-static elements from a static method.

Non-static elements (e.g. your fxn (int y)) can only be called from an instance of your class.

Example:

You can do it:

  public class A { public int fxn(int y) { y = 5; return y; } } class Two { public static void main(String[] args) { int x = 0; A a = new A(); System.out.println("x = " + x); x = a.fxn(x); System.out.println("x = " + x); } 

or you can declare your method static.

+1
source
  • A static method can NOT access a non-stationary method or variable.

  • public static void main(String[] args) is a static method, so it can NOT access the non-stationary method public static int fxn(int y) .

  • Try it this way ...

    static int fxn (int y)

     public class Two { public static void main(String[] args) { int x = 0; System.out.println("x = " + x); x = fxn(x); System.out.println("x = " + x); } static int fxn(int y) { y = 5; return y; } 

    }

0
source

All Articles