Java中的内部类必须是静态的吗?

Pra*_*een 4 java static

我创建了一个非静态内部类,如下所示:

class Sample {
    public void sam() {
        System.out.println("hi");
    }    
}
Run Code Online (Sandbox Code Playgroud)

我用这样的main方法调用它:

Sample obj = new Sample();
obj.sam();
Run Code Online (Sandbox Code Playgroud)

它给出了一个编译错误:non-static cannot be referenced from a static context当我将非静态内部类声明为静态时,它起作用.为什么会这样?

Ash*_*Ash 10

对于非静态内部类,编译器会自动向"owner"对象实例添加隐藏引用.当您尝试从静态方法(例如,main方法)创建它时,没有拥有实例.这就像尝试从静态方法调用实例方法 - 编译器不允许它,因为您实际上没有要调用的实例.

因此内部类本身必须是静态的(在这种情况下不需要拥有实例),或者只在非静态上下文中创建内部类实例.


Sea*_*oyd 5

非静态内部类将外部类作为实例变量,这意味着只能从外部类的此类实例进行实例化:

public class Outer{
    public class Inner{
    }

    public void doValidStuff(){
         Inner inner = new Inner();
         // no problem, I created it from the context of *this*
    }

    public static void doInvalidStuff(){
         Inner inner = new Inner();
         // this will fail, as there is no *this* in a static context
    }

}
Run Code Online (Sandbox Code Playgroud)