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

编程入门 行业动态 更新时间:2024-10-09 07:28:47

JAVA eclipse<a href=https://www.elefans.com/category/jswz/34/1771188.html style=报错:No enclosing instance of type testmain is accessible. Must qualify the allocation wit"/>

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{@Overridepublic 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=w;Person p2=new Person();p2=l;p1.useMyComputer();p2.useMyComputer();}
}

第一种解决方法:

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

修改后的代码

package testpackeg;
abstract class Computer
{public abstract void use();
}
class Windows extends Computer
{@Overridepublic 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=w;Person p2=new Person();p2=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{@Overridepublic 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=w;Person p2=new Person();p2=l;p1.useMyComputer();p2.useMyComputer();}
}

更多推荐

JAVA eclipse报错:No enclosing instance of type testmain is accessible. Must qualif

本文发布于:2024-02-07 06:24:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754228.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:报错   enclosing   instance   eclipse   JAVA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!