如何在静态方法中实例化非静态内部类

Vic*_*jee 114 java static inner-classes

我有以下代码:

public class MyClass {

   class Inner {
     int s, e, p;
   }

   public static void main(String args[]) {
     Inner in;
   }
}
Run Code Online (Sandbox Code Playgroud)

到这一部分代码很好,但是我无法像in = new Inner()在显示那样在main方法中实例化'in' non static field cannot be referenced in static context.我能用它做什么?我不想让我的内部类静态.

RNJ*_*RNJ 190

您还必须引用其他外部类.

Inner inner = new MyClass().new Inner();
Run Code Online (Sandbox Code Playgroud)

如果Inner是静态的那么它就是

Inner inner = new MyClass.Inner();
Run Code Online (Sandbox Code Playgroud)

  • 这个答案改变了我的人生观.outer.new Inner()?从来没有考虑过这种可能性.O_O (50认同)
  • 对于静态内部,你不能简单地执行 Inner inner = new Inner() 吗? (2认同)

Chr*_*ell 37

"常规"内部类具有指向外部类实例的隐藏(隐式)指针.这允许编译器生成代码以便为您追逐指针而无需键入它.例如,如果外部类中有变量"a",那么内部类中的代码只能执行"a = 0",但编译器将生成"outerPointer.a = 0"的代码,并将隐藏指针保持在封面.

这意味着当您创建内部类的实例时,您必须具有外部类的实例以将其链接到.如果在外部类的方法中进行此创建,则编译器知道使用"this"作为隐式指针.如果要链接到其他外部实例,则使用特殊的"新"语法(请参阅下面的代码段).

如果你使你的内部类"静态",那么没有隐藏的指针,你的内部类不能引用外部类的成员.静态内部类与常规类相同,但其名称在父级内部作用域.

下面是一段代码,演示了创建静态和非静态内部类的语法:

public class MyClass {

    int a,b,c; // Some members for MyClass

    static class InnerOne {
        int s,e,p;
        void clearA() {
            //a = 0;  Can't do this ... no outer pointer
        }
    }

    class InnerTwo {
        //MyClass parentPointer;      Hidden pointer to outer instance
        void clearA() {         
            a = 0;
            //outerPointer.a = 0      The compiler generates this code
        }       
    }

    void myClassMember() {
        // The compiler knows that "this" is the outer reference to give
        // to the new "two" instance.
        InnerTwo two = new InnerTwo(); //same as this.new InnerTwo()
    }

    public static void main(String args[]) {

        MyClass outer = new MyClass();

        InnerTwo x = outer.new InnerTwo(); // Have to set the hidden pointer
        InnerOne y = new InnerOne(); // a "static" inner has no hidden pointer
        InnerOne z = new MyClass.InnerOne(); // In other classes you have to spell out the scope

    }

}
Run Code Online (Sandbox Code Playgroud)