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

  • 相关阅读:
    下载安装安卓开发工具
    斐波那契数列
    各位相加
    求连续最大子序列和
    反转字符串中的单词
    统计位数为偶数的数字
    Express框架的整体感知
    node.js当中的http模块与url模块的简单介绍
    formidable处理提交的表单或文件的简单介绍
    30分钟,学会经典小游戏编程!
  • 原文地址:https://www.cnblogs.com/otakus/p/12164732.html
Copyright © 2011-2022 走看看