不能访问类型为mProgram的封闭实例。必须使用mProgram类型的封闭实例限定分配

时间:2013-05-31 13:02:03

标签: java class syntax-error

我正在尝试从我的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).

任何帮助我如何解决这个问题都很棒

2 个答案:

答案 0 :(得分:0)

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

EG:

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();
  }

}

答案 1 :(得分: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();
    }
}