zoukankan      html  css  js  c++  java
  • No enclosing instance of type XXX is accessible.

    一个类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<Artist> 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;
            }
    
        }
    
    }
    

    这里写图片描述

  • 相关阅读:
    前端js实现复制功能
    vue中流文件下载
    vuex的module简单使用
    vuex及其辅助函数简单使用
    element中合并单元格操作
    js保留小数并四舍五入方法封装
    数组的基本属性和方法
    数组的深复制、扁平化、排序及去重相关方法
    js基本数据类型及数组对象判断
    for/in 语句用于循环对象属性
  • 原文地址:https://www.cnblogs.com/DiZhang/p/12545032.html
Copyright © 2011-2022 走看看