Java编译时出现 No enclosing instance of type Main is accessi

php中文网
发布: 2016-06-07 15:50:03
原创
2005人浏览过

今天在编译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静态的。

立即学习Java免费学习笔记(深入)”;

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

有两种解决办法:

第一种:

将内部类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;}
}
登录后复制


豆包AI编程
豆包AI编程

智能代码生成与优化,高效提升开发速度与质量!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号