博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
No enclosing instance of type XXX is accessible.
阅读量:4059 次
发布时间:2019-05-25

本文共 1705 字,大约阅读时间需要 5 分钟。

一个类LambdaChapter3 中有另一个类Artist (外部类和内部类), 如果使用new 的方式创建内部类的对象,会报错:No enclosing instance of type LambdaChapter3 is accessible.

报错信息:

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

原因:

内部类是动态的(无static关键字修饰),而main方法是静态的,普通的内部类对象隐含地保存了一个引用,指向创建它的外围类对象,所以要在static方法(类加载时已经初始化)调用内部类的必须先创建外部类。

解决方法:

创建内部类对象应该:
方法1:外部类对象.内部类对象 (保证外部类对象先于内部类对象出现)

DanymicTest test = new StaticCallDynamic().new DanymicTest();

其中StaticCallDynamic为外部类,DanymicTest为内部动态类;

方法2:
如果将内部类修改为静态类,可以在main中直接创建内部类实例。

//外部类LambdaChapter3 public class LambdaChapter3 {    public static void main(String[] args) {        ArrayList
allArtists = new ArrayList(); //Artist artist = new LambdaChapter3().new Artist("zhangsan", "London"); Artist artist = new Artist("zhangsan", "London"); allArtists.add(artist); artistNationnal_java8(allArtists); } //内部类 Artist class Artist { private String name; private String city; public Artist(String name, String city) { super(); this.name = name; this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public boolean isFrom(String string) { return string.equals("London"); } public void setIsFrom(String isFrom) { this.city = isFrom; } }}

这里写图片描述

你可能感兴趣的文章
Jenkins + Docker + SpringCloud 微服务持续集成 - 单机部署(二)
查看>>
Jenkins + Docker + SpringCloud 微服务持续集成 - 高可用集群部署(三)
查看>>
Golang struct 指针引用用法(声明入门篇)
查看>>
Linux 粘滞位 suid sgid
查看>>
C#控件集DotNetBar安装及破解
查看>>
Winform皮肤控件IrisSkin4.dll使用
查看>>
Winform多线程
查看>>
C# 托管与非托管
查看>>
Node.js中的事件驱动编程详解
查看>>
mongodb 命令
查看>>
MongoDB基本使用
查看>>
mongodb管理与安全认证
查看>>
nodejs内存控制
查看>>
nodejs Stream使用中的陷阱
查看>>
MongoDB 数据文件备份与恢复
查看>>
数据库索引介绍及使用
查看>>
MongoDB数据库插入、更新和删除操作详解
查看>>
MongoDB文档(Document)全局唯一ID的设计思路
查看>>
mongoDB简介
查看>>
Redis持久化存储(AOF与RDB两种模式)
查看>>