zoukankan      html  css  js  c++  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 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内要加不然就报错。

  • 相关阅读:
    软件工程—附加作业
    软件工程最终总结
    电梯调度(两人结对)
    VS单元测试
    第二周作业(2,3题)
    VS的安装
    补救
    漂亮男孩不说谎
    博客带我成长
    Java后缀数组-求sa数组
  • 原文地址:https://www.cnblogs.com/otakus/p/12164732.html
Copyright © 2011-2022 走看看