您的位置:首页 > 编程语言 > Java开发

Java编译时出现No enclosing instance of type XXX is accessible.

2015-04-11 18:05 651 查看
今天在编译Java程序的时候出现以下错误:

NoenclosinginstanceoftypeMainisaccessible.MustqualifytheallocationwithanenclosinginstanceoftypeMain(e.g.x.newA()wherexisaninstanceofMain).

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

publicclassMain
{
classDog//定义一个“狗类”
{
privateStringname;
privateintweight;
publicDog(Stringname,intweight)
{
this.setName(name);
this.weight=weight;
}
publicintgetWeight()
{
returnweight;
}
publicvoidsetWeight(intweight)
{this.weight=weight;}
publicvoidsetName(Stringname)
{this.name=name;}
publicStringgetName()
{returnname;}
}
publicstaticvoidmain(String[]args)
{
Dogd1=newDog("dog1",1);

}
}

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

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

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

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

有两种解决办法:

第一种:

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

第二种:

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

修改后的代码:

第一种:

?
第二种:

?


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐