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

时间:2024-01-07 14:32:20
No enclosing instance of type Demo is accessible. Must qualify the allocation with an enclosing instance of type Demo (e.g. x.new A() where 
x is an instance of Demo).

在练习一Demo时,遇到上面的编译时错误

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

原因:main是Test类的static方法,按照常理它只能访问Test类中static资源,而class A是非static所以报错了。

解决方法一:给class F添加static属性。

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

解决方法二: 没有必要把F放在Demo中做内部类,将它移到Demo外部地方定义。

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