Java 错误之“No enclosing instance of type XXX is accessible”

一、问题描述

在一个类的main( )函数中调用该类的内部类时,报错。错误信息如下:

- No enclosing instance of type Bounce is accessible. Must qualify the allocation with an enclosing instance of type Bounce (e.g. x.new A() where x is an instance of Bounce).


二、问题原因

main( )函数是静态的(static);而内部类由于无static修饰,因此是非静态的(non-static)。我们在static方法创建内部类的时候,必须先创建外部类。


三、问题解决

在static方法内创建内部类时,先创建外部类。比如:

innerClass :内部类

outerClass :外部类

innerClass ic = new outerClass().new innerClass();
发布了26 篇原创文章 · 获赞 9 · 访问量 8221

猜你喜欢

转载自blog.csdn.net/weixin_41664064/article/details/104298820