在上述代码中,报错的原因是使用了循环引用。在类Person中,定义了一个成员变量p,类型为Person。然后在类ZiLei的main方法中,实例化了一个Star对象s,并调用了s.eat()方法。

在eat()方法中,又创建了一个Person对象p,并将其赋值给成员变量p。但是在创建Person对象p的过程中,又会调用Person的构造函数,其中又会创建一个Person对象p,如此循环引用导致了栈溢出错误。

为了解决这个问题,可以将类Person中的成员变量p的定义移动到eat()方法中,即改为:

public void eat(){ Person p = new Person(); p.name="dwd"; System.out.println(p.name); } 这样就避免了循环引用的问题。

public class ZiLei public static void mainString args Star s = new Star; seat; Systemoutprintln====; ssing; class Person String name; Person p = new Person;

原文地址: http://www.cveoy.top/t/topic/iiti 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录