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
fieldarr
得到了地址值
这就是我的理解,我错了吗 当实例化非静态嵌套类(即
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
是在staticmain
方法的上下文中实例化的,因此没有此类封闭的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;
}
}