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;
            }
    
        }
    
    }
    

    这里写图片描述

  • 相关阅读:
    高效沟通
    Oracle播放多条 INSERT ALL
    oracle的同义词总结
    Brute force Attack
    爱因斯坦方程与小黑洞
    dom 编程(html和xml)
    dexposed框架Android在线热修复
    从微软小冰看微软运营手段的转型
    剑指offer_面试题_从上往下打印二叉树
    外面的wifi非常精彩,外面的wifi非常不安
  • 原文地址:https://www.cnblogs.com/DiZhang/p/12545032.html
Copyright © 2011-2022 走看看