本文共 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) { ArrayListallArtists = 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; } }}