简体   繁体   中英

Why calling this function in the constructor creates stackoverflow error?

Hi I have a Person class which has a method fatherComesFirst which instantiates a Person father . However, when I call this method in the constructor why does the jvm throw the stackoverflow error? I am beginner. Although I believe so far I am correct.

My Code.

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());
    }

}

Because whenever you create an instance of the Person() class, it calls the function fatherComesFirst() which, on the first line of that function, creates another instance of the same class. This is an infinite loop.

That is essentially an infinite loop. Whenever the constructor is hit, it calls a function that instantiates another Person. When this Person is being instantiated, it also calls the same function that instantiates another Person, which in construction also calls that function...well you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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