繁体   English   中英

为什么在构造函数中调用此函数会产生stackoverflow错误?

[英]Why calling this function in the constructor creates stackoverflow error?

嗨,我有一个Person类,它有一个方法fatherComesFirst ,它实例化Person father 但是,当我在构造函数中调用此方法时, jvm为什么会引发stackoverflow错误? 我是初学者。 尽管我相信到目前为止我是正确的。

我的代码。

package intermediate;

public class Person {

    //getters & setters

    private String firstName;

    private String lastName;

    public Person(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
        fatherComesFirst("",lastName);
    }

    public void fatherComesFirst(String firstName, String lastName){
        Person father = new Person(firstName,lastName);
        System.out.println(father.getFirstName()+" "+father.getLastName());
    }

}

因为每当您创建Person()类的实例时,它都会调用函数fatherComesFirst() ,该函数在该函数的第一行上创建同一类的另一个实例。 这是一个无限循环。

这本质上是一个无限循环。 每当构造函数被命中时,它都会调用一个实例化另一个Person的函数。 当实例化此Person时,它还会调用与实例化另一个Person相同的函数,在构造中,该函数也会调用该函数...那么您就会明白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM