0
public class Test {
    class Foo {
        int[] arr;
        Foo(int[] userInput) {
            arr = userInput;
        }
    }
    public static void main(String[] args) {
        int[] userInput = new int[]{1,2,3,4,5};
        Foo instance = new Foo(userInput);
    }
}

It gave me an error

error: non-static variable this cannot be referenced from a static context

I already have searched some answers but cannot cannot solve it.

Here's how I think about this code, I view userInput as a pointer, and the compiler allocate five int memory and assign userInput with a address, then I transfer this address (I know java is pass by value) to class Foo constructor, and I think instance field arr got the address value.

That's how I understand, am I wrong?

DoubleX
  • 351
  • 3
  • 18

2 Answers2

3

Since class Foo is a non static inner class of class Test, an instance of class Foo can not exists without an instance of Test. So either change Foo to be static:

static class Foo {
    int[] arr;
    Foo(int[] userInput) {
        arr = userInput;
    }
}

or if you don't want to make it static then change the way you create an instance of Foo via an instance of Test:

Foo instance = new Test().new Foo(userInput);
STaefi
  • 4,297
  • 1
  • 25
  • 43
2

When non-static nested classes (i.e. Foo) are instantiated, such as with new Foo(userInput), they need to store an implicit reference to the this variable of their enclosing class (i.e. Test). Since Foo is instantiated within the context of the static main method, no such instance of the enclosing Test is available. Thus, an error is thrown. The way to fix this is to make the nested class Foo static, as in:

public class Test {
    static class Foo {   // <---- Notice the static class
        int[] arr;
        Foo(int[] userInput) {
            arr = userInput;
        }
    }
    public static void main(String[] args) {
        int[] userInput = new int[]{1,2,3,4,5};
        Foo instance = new Foo(userInput);
    }
}

For more information, see the Nested Classes documentation and Why do I get “non-static variable this cannot be referenced from a static context”?

Justin Albano
  • 3,809
  • 2
  • 24
  • 51