java如何将主数组正确地传递给类构造函数?

java如何将主数组正确地传递给类构造函数?,java,memory,Java,Memory,它给了我一个错误 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 insta

它给了我一个错误

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);
    }
}
我已经找到了一些答案,但无法解决它

下面是我对这段代码的看法,我将
userInput
视为一个指针,编译器分配五个
int
内存并给userInput分配一个
地址
,然后我将这个地址(我知道java是
按值传递
)传递给类
Foo
构造函数,我认为
instance
field
arr
得到了地址值


这就是我的理解,我错了吗

当实例化非静态嵌套类(即
Foo
)时,例如使用
new Foo(userInput)
,它们需要存储对其封闭类(即
Test
)的
变量的隐式引用。由于
Foo
是在静态
main
方法的上下文中实例化的,因此没有包含
Test
的实例可用。因此,抛出一个错误。解决此问题的方法是将嵌套类
Foo
设置为静态,如下所示:

error: non-static variable this cannot be referenced from a static context
公共类测试{

静态类Foo{//当实例化非静态嵌套类(即
Foo
)时,例如使用
newfoo(userInput)
,它们需要存储对其封闭类(即
Test
)的
变量的隐式引用。由于
Foo
是在static
main
方法的上下文中实例化的,因此没有此类封闭的
Test
实例可用。因此,会引发错误。解决此问题的方法是使嵌套类
Foo
保持静态,如下所示:

error: non-static variable this cannot be referenced from a static context
公共类测试{

静态类Foo{//由于类
Foo
是类
Test
的非静态内部类,没有
Test
的实例,类
Foo
的实例就不可能存在。因此,要么将
Foo
更改为
static

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);
    }
}
或者,如果您不想使其成为
静态的
,请通过
测试的实例更改创建
Foo
实例的方式:

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

由于类
Foo
是类
Test
的非静态内部类,没有
Test
的实例,类
Foo
的实例就不可能存在。因此将
Foo
更改为
静态

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);
    }
}
或者,如果您不想使其成为
静态的
,请通过
测试的实例更改创建
Foo
实例的方式:

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