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

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

This question is related to java

The answer is


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.


  1. A static method can NOT access a Non-static method or variable.

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

  3. 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;
        }
    

    }


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.

Example:

You can do this:

       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 you method as static.


You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:

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

That is, make a Two-Object and call the method on that object.

...or make the fxn method static.