【问题标题】:java how to pass main array to class constructor correctly? [duplicate]java如何正确地将主数组传递给类构造函数? [复制]
【发布时间】:2018-04-08 11:19:35
【问题描述】:
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);
    }
}

它给了我一个错误

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

我已经搜索了一些答案,但无法解决。

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

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

【问题讨论】:

    标签: java memory


    【解决方案1】:

    由于类Foo 是类Test 的非静态内部类,因此如果没有Test 的实例,类Foo 的实例就不能存在。所以要么把Foo改成static

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

    或者如果您不想创建static,那么通过Test 的实例更改创建Foo 实例的方式:

    Foo instance = new Test().new Foo(userInput);
    

    【讨论】:

      【解决方案2】:

      当实例化非静态嵌套类(即Foo)时,例如使用new Foo(userInput),它们需要存储对其封闭类(即Test)的this变量的隐式引用。由于Foo 是在静态main 方法的上下文中实例化的,因此没有可用的封闭Test 的此类实例。因此,抛出错误。解决这个问题的方法是使嵌套类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);
          }
      }
      

      有关详细信息,请参阅 Nested Classes 文档和 Why do I get “non-static variable this cannot be referenced from a static context”?

      【讨论】:

        猜你喜欢
        • 2019-08-21
        • 1970-01-01
        • 2022-01-12
        • 2018-08-04
        • 2011-12-05
        • 2012-03-14
        • 1970-01-01
        • 2012-09-11
        • 1970-01-01
        相关资源
        最近更新 更多