zoukankan      html  css  js  c++  java
  • 解决No enclosing instance of type * is accessible

    写一个内部类,并在构造函数中初始化时,遇到报错,搜索问题后发现,有网友出现过类似的问题,下面这个是说的浅显明白的,并确实解决了问题。于是,以下内容照搬过来,不再多费键盘了。

    public class Test_drive {
      
      public static void main(String[] args){
        A a = new A();              //报错
        B b = new B();              //报错
        System.out.println(b instanceof A);
      }
      class A{
        int a;
      }
      class B extends A{
      }
    }

    上面两个语句报错信息如下:

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

    在overflow上面查找到了类似的问题:http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible/9560633#9560633

    下面简单说一下我的理解:

    在这里,A和B都是Test_drive的内部类,类似于普通的实例变量,如类的静态方法不可以直接调用类的实例变量。在这里,内部类不是静态的内部类,所以,直接赋值(即实例化内部类),所以程序报错。

    解决的方法可以有以下两种:

    (1)将内部类定义为static,即为静态类

    (2)将A a = new A();B b = new B();改为:

    Test_drive td = new Test_drive();
    A a = td.new A();
    B b = td.new B();
  • 相关阅读:
    linux ps查看进程命令
    linux distribution是什么?
    samba配置smb.conf
    linux samba.tar.gz安装和配置
    linux后台执行命令&
    linux crontab任务调度的使用
    linux ubuntu卸载软件
    vue-router
    vue computed
    vue 监听的使用
  • 原文地址:https://www.cnblogs.com/data2value/p/5579472.html
Copyright © 2011-2022 走看看