0

我试图从我的 NrlData 类中调用,但以下行一直给我一个错误

public static class NrlMain {
    public static void main(String[] args) {
        NrlData nrlData = new NrlData();//No enclosing instance of type mProgram is accessible. Must qualify the allocation with an enclosing instance of type mProgram (e.g. x.new A() where x is an instance of mProgram).

任何有关我如何解决的帮助都会很棒

4

2 回答 2

0

您需要创建您的NrlDatastatic或从封闭类的实例创建它。

例如:

public static class NrlMain {
  static String aStaticVariable = "Static";
  String anInstanceVariable = "Hello";

  private class NrlData {
    // We CAN do this because there is always a parent `Object` of type `NrlMain`.
    String hello = anInstanceVariable;
    // We CAN also access static variables.
    String s = aStaticVariable;
  }

  private static class NrlStaticData {
    // We CANNOT do this because there is no parent object.
    //String hello = anInstanceVariable;
    // We CAN access static variables.
    String s = aStaticVariable;
  }

  public static void main(String[] args) {
    // Fails
    //NrlData nrlData = new NrlData();
    NrlData nrlData = new NrlMain().new NrlData();
    NrlStaticData nrlStaticData = new NrlStaticData();
  }

}
于 2013-05-31T13:10:22.290 回答
0

在创建内部类的实例之前,您必须首先创建 mProgram 的实例,或者您可以将内部类(在这种情况下为 NrlData)声明为静态,但您仍然需要 mProgram 类来访问它(但您不需要必须实例化它。

public class mProgram {
    public class NrlData {
        ...
    }

    public static void main(String[] args) {
        mProgram.NrlData nrlData = new mProgram().new NrlData();
    }

    public void aMethod() { // accessing inner class from the "this" instance
        NrlData nrlData = new NrlData();
}

或者

public class mProgram {
    public static class NrlData {
        ...
    }

    public static void main(String[] args) {
        mProgram.NrlData nrlData = new mProgram.NrlData();
    }
}

仅以第一种情况为例,其中 NrlData 不是静态的。

在 mProgram 类的非静态函数中,您不需要创建 mProgram 实例,因为它使用this实例。

现在,如果您尝试从另一个类访问内部类,因为您没有任何 mProgram 实例,您必须首先创建该实例。这就是为什么您只在 NrlMain 而在 mProgram 中没有问题的原因。

public class NrlMain {
    public void accessingInnerClass() {
        // Creating the mProgram instance
        mProgram mprogram = new mProgram();
        // Creating inner class instance
        mProgram.NrlData nrlData = mprogram.new NrlData();
    }
}
于 2013-05-31T13:28:38.950 回答