Java中出现No enclosing instance of type XXX is accessible问题

下面是我的代码:

public class TraditionalThreadSynchronized {
        public static void main(String[] args) {        
        //OutPuter outPuter = new TraditionalThreadSynchronized ().new OutPuter(); //true
        OutPuter outPuter = new OutPuter(); //false
        new Thread(new Runnable(){
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    outPuter.outPut("abcdefghjik");
                }
            }
        }).start();
    }

    class OutPuter{
        public void outPut(String name){
            int len = name.length();
            for(int i=0; i<len; i++){
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }
    }
}

OutPuter 是一个普通的内部类,当我使用下面这个语句创建OutPuter 的实例对象是报错(No enclosing instance of type TraditionalThreadSynchronized is accessible. Must qualify the allocation with an enclosing instance of type TraditionalThreadSynchronized (e.g. x.new A() where x is an instance of TraditionalThreadSynchronized ).):

OutPuter outPuter = new OutPuter(); 

我在main方法中创建内部类的实例时出错,是因为普通的内部类是动态的(无static关键字修饰),而main方法是静态的,普通的内部类对象隐含地保存了一个引用,指向创建它的外围类对象,所以要在static方法(类加载时已经初始化)调用内部类的必须先创建外部类。即应该这样创建“OutPuter outPuter = new TraditionalThreadSynchronized().new OutPuter();”其中TraditionalThreadSynchronized 为外部类,OutPuter 为内部动态类;如果将内部内修改为静态类,可以在main中直接创建内部类实例。

转载自文章:
https://www.cnblogs.com/runnigwolf/p/5570810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值