视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
Java编译时出现NoenclosinginstanceoftypeMainisaccessi
2020-11-09 07:19:23 责编:小采
文档

今天在编译Java程序的时候出现以下错误: No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main). 我原来编写的源代码是这样的: publ

今天在编译Java程序的时候出现以下错误:

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


我原来编写的源代码是这样的:

public class Main
{
class Dog //定义一个“狗类”
{
private String name;
private int weight;
public Dog(String name, int weight)
{
this.setName(name);
this.weight = weight;
}
public int getWeight()
{
return weight;
}
public void setWeight(int weight)
{this.weight = weight;}
public void setName(String name)
{this.name = name;}
public String getName()
{return name;}
}
public static void main(String[] args)
{
Dog d1 = new Dog("dog1",1);

}
}

出现这个错误的时候,我一直不太理解。

在借鉴别人的解释之后才恍然大悟。

在代码中,我的Dog类是定义在Main中的内部类。Dog内部类是动态的内部类,而我的main方法是static静态的。

就好比静态的方法不能调用动态的方法一样。

有两种解决办法:

第一种:

将内部类Dog定义成静态static的类。

第二种:

将内部类Dog在Main类外边定义。


修改后的代码:

第一种:

public class Main 
{
	public static class Dog 
	{
	private String name;
	private int weight;
	public Dog(String name, int weight) 
	{
	this.setName(name);
	this.weight = weight;
	}
	public int getWeight() 
	{
	return weight;
	}
	public void setWeight(int weight) 
	{this.weight = weight;}
	public void setName(String name)
	{this.name = name;}
	public String getName() 
	{return name;}
	}
	public static void main(String[] args)
	{
	Dog d1 = new Dog("dog1",1);	
	}
}


第二种:

public class Main 
{
	public static void main(String[] args)
	{
	Dog d1 = new Dog("dog1",1);	
	}
}

class Dog 
{
	private String name;
	private int weight;
	public Dog(String name, int weight) 
	{
	this.setName(name);
	this.weight = weight;
	}
	public int getWeight() 
	{
	return weight;
	}
	public void setWeight(int weight) 
	{this.weight = weight;}
	public void setName(String name)
	{this.name = name;}
	public String getName() 
	{return name;}
}

下载本文
显示全文
专题