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内要加不然就报错。

  • 相关阅读:
    C#可视化程序设计第三章(3,4)
    "Can’t be opened because Apple cannot check it for malicious software" 解决方案
    Mac系统.DS_Store文件导致IOError: [Errno 20] Not a directory:解决方案
    读书笔记 《局外人》
    Chrome 67之后无法离线安装插件
    函数和方法的区别
    github|webstorm
    webstorm
    Markdown
    github
  • 原文地址:https://www.cnblogs.com/otakus/p/12164732.html
Copyright © 2011-2022 走看看