内部类的使用问题No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclo...

来自下面的连接,我遇到了百度发现有人写了,就直接引用过来了。

感谢!

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

 

之前看内部类的时候没发现这个问题,今天写代码的时候遇到,写个最简单的例子:

下面这一段代码

19170657_WJJC.png

红色的部分就是编译报错:

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

根据提示,没有可以访问的实例Outer,必须分配一个合适的外部类实例以访问内部类。

正确的方式可以是:

public class Outer {
    private int i = 10;
    class Inner{
        public void seeOuter(){
            System.out.println(i);
        }
    }
    public static void main(String[] args) {
        Outer out = new Outer();
        Inner in = out.new Inner();
        in.seeOuter();
    }
}

或者:

public class Outer {
    private int i = 10;
    static class Inner{
        public void seeOuter(){
            // 静态内部类不能直接访问外部类的非静态成员,但可以通过 new 外部类().成员 的方式访问 
            //System.out.println(i);这句话编译不过
            System.out.println(new Outer().i);
        }
    }
    
    public static void main(String[] args) {
        Inner in = new Inner();
        in.seeOuter();
    }
}

关于内部类

  • 依然是一个独立的类,在编译之后会内部类会被编译成独立的.class文件,但是前面冠以外部类的类命和$符号。
  • 内部类不能用普通的方式访问。内部类是外部类的一个成员,因此内部类可以自由地访问外部类的成员变量,无论是否是private的。
  • 成员内部类内不允许有任何静态声明!
  • 能够访问成员内部类的唯一途径就是通过外部类的对象!

有关内部类具体可参考
http://blog.csdn.net/ft305977550/article/details/8350708

仅仅记录编程中遇到的问题。

转载于:https://my.oschina.net/zjllovecode/blog/904533

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值