当前位置: 移动技术网 > IT编程>开发语言>Java > No enclosing instance of type test is accessible. Must qualify the allocation with an enclosing inst

No enclosing instance of type test is accessible. Must qualify the allocation with an enclosing inst

2020年01月08日  | 移动技术网IT编程  | 我要评论
今日遇到一个报错如下: No enclosing instance of type test is accessible. Must qualify the allocation with an enclosing instance of type test (e.g. x.new A() wher ...

今日遇到一个报错如下:

 

 

no enclosing instance of type test is accessible. must qualify the allocation with an enclosing instance of type test (e.g. x.new a() where x is an instance of test).
问题出现的原因是:

        因为在做demo测试,我写的内部类是动态的,即public class开头无static关键字修饰,而测试主程序是静态的main方法。在java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,才可以再静态类中调用带类的成员变量和成员方法。
        为什么静态方法不能直接访问非静态成员呢?
        静态成员是在jvm的classloader加载类的时候初始化的,而非静态成员是在创建对象,也就是new操作的时候才初始化的。类加载的时候初始化的静态成员已经分配内存空间,所以可以访问,而非静态成员还没有通过new创建对象而进行初始化,所有当然不能访问了。
解决方案:

        1.将动态内部类改为静态(public static class)。

        2.将内部类改为外部类。

        3.别用静态main方法调用。

在class外不用加static

而在class内要加不然就报错。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网