No enclosing instance of type TestInner is accessible.

深夜,临睡前写了个小程序,出了点小问题

public class TestInner{
    
    public static void main(String[] args){
        A a = new A();              //报错
        B b = new B();              //报错
        System.out.println(b instanceof A);
    }
    class A{
        int a;
    }
    class B extends A{
    }
}

上面两个语句报错信息如下:

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

(1)在stackoverflow上面查找到了类似的问题:http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible/9560633#9560633

(2)下面简单说一下我的理解:

  在这里,A和B都是Test_drive的内部类,类似于普通的实例变量,如果类的静态方法不可以直接调用类的实例变量。在这里,内部类不是静态的内部类,所以,直接赋值(即实例化内部类),所以程序报错。

 

(3)解决的方法可以有以下两种:

  (1)将内部类定义为static,即为静态类

  (2)将A a = new A();B b = new B();改为:

TestInner td = new TestInner();
A a = td.new A();
B b = td.new B();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值