Java编译时出现 No enclosing instance of type Main is accessible. Must qualify the allocation with an encl

拼搏现实的明天。 2022-07-13 11:48 301阅读 0赞

今天在编译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).

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

  1. public class Main
  2. {
  3. class Dog //定义一个“狗类”
  4. {
  5. private String name;
  6. private int weight;
  7. public Dog(String name, int weight)
  8. {
  9. this.setName(name);
  10. this.weight = weight;
  11. }
  12. public int getWeight()
  13. {
  14. return weight;
  15. }
  16. public void setWeight(int weight)
  17. {
  18. this.weight = weight;}
  19. public void setName(String name)
  20. {
  21. this.name = name;}
  22. public String getName()
  23. {
  24. return name;}
  25. }
  26. public static void main(String[] args)
  27. {
  28. Dog d1 = new Dog("dog1",1);
  29. }
  30. }

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

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

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

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

有两种解决办法:

第一种:

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

第二种:

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

原文

发表评论

表情:
评论列表 (有 0 条评论,301人围观)

还没有评论,来说两句吧...

相关阅读