当前位置: 首页 > 工具软件 > OFTest > 使用案例 >

JAVA编译报错-No enclosing instance of type Test is accessible

羊丰茂
2023-12-01

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方法(类加载时已经初始化)调用内部类的必须先创建外部类。

 类似资料: