JAVA eclipse报错:No enclosing instance of type testmain is accessible. Must qualify the allocation wit

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

出错的原因:main函数是静态的,不能调用动态的内部类。

出错的代码如下:

package testpackeg;

public class testmain {
	abstract class Computer
	{
		public abstract void use();
	}
	class Windows extends Computer
	{
		@Override
		public void use()
		{
			System.out.println("windows");
		}
	}
	class Linux extends Computer
	{
		public void use()
		{
			System.out.println("linux");
		}
	}
	class Person
	{
		Computer com;
		void useMyComputer()
		{
			com.use();
		}
	}
	
	public static void main(String[] args)
	{
		Computer w=new Windows();
		Computer l=new Linux();
		Person p1=new Person();
		p1.com=w;
		Person p2=new Person();
		p2.com=l;
		p1.useMyComputer();
		p2.useMyComputer();
	}
}

第一种解决方法:

把内部类改为外部类。内部类是指定义在一个类中的类。在出错代码中,computer、windows都定义在了testmain类中。将这些类挪出去就行了。

修改后的代码

package testpackeg;
abstract class Computer
{
	public abstract void use();
}
class Windows extends Computer
{
	@Override
	public void use()
	{
		System.out.println("windows");
	}
}
class Linux extends Computer
{
	public void use()
	{
		System.out.println("linux");
	}
}
class Person
{
	Computer com;
	void useMyComputer()
	{
		com.use();
	}
}
public class testmain {
	//把原来在这里定义的类挪走了
	
	public static void main(String[] args)
	{
		Computer w=new Windows();
		Computer l=new Linux();
		Person p1=new Person();
		p1.com=w;
		Person p2=new Person();
		p2.com=l;
		p1.useMyComputer();
		p2.useMyComputer();
	}
}

第二种解决方法:

在定义的类前面加上static,将动态内部类变成静态的。

package testpackeg;

public class testmain {
	abstract static class Computer//前面加了abstract修饰
	{
		public abstract void use();
	}
	static class Windows extends Computer
	{
		@Override
		public void use()
		{
			System.out.println("windows");
		}
	}
	static class Linux extends Computer
	{
		public void use()
		{
			System.out.println("linux");
		}
	}
	static class Person
	{
		Computer com;
		void useMyComputer()
		{
			com.use();
		}
	}
	
	public static void main(String[] args)
	{
		Computer w=new Windows();
		Computer l=new Linux();
		Person p1=new Person();
		p1.com=w;
		Person p2=new Person();
		p2.com=l;
		p1.useMyComputer();
		p2.useMyComputer();
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值