java编译出错:
No enclosing instance of type Test is accessible. Must qualify the allocation with an enclosing instance of type Test (e.g. x.new A() where x is an instance of Test).
代码demo
public class Test
{
interface Some
{
void dosome();
}
interface Other
{
void doOther();
}
class SomeImpl implements Some,Other
{
@Override
public void dosome()
{
System.out.println("hha");
}
@Override
public void doOther()
{
System.out.println("123");
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
//Some some = new Test().new SomeImpl();
Some some = new SomeImpl();
some.dosome();
Other other = (Other)some;
other.doOther();
}
}解决方式:
报错代码改为Some some = new Test().new SomeImpl();即可
原因是是因为内部类是动态的(无static关键字修饰),而main方法是静态的,普通的内部类对象隐含地保存了一个引用,指向创建它的外围类对象,所以要在static方法(类加载时已经初始化)调用内部类的必须先创建外部类。
本文介绍了一种常见的Java编译错误:尝试从静态上下文中访问非静态内部类实例时出现的错误。通过一个示例解释了如何正确创建内部类对象,并讨论了内部类与外部类之间的关系。
381

被折叠的 条评论
为什么被折叠?



