stackoverflow error in class constructor

The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? …

public Name(String name)
{
    Name employeeName = new Name(name);  // **** YIKES!! ***
    this.name = employeeName;
}

Bingo: recursion!

This constructor will create a new Name object whose constructor will create a new Name object whose constructor will… and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don’t do this. Assign name to a String:

class Name {
    String name; // ***** String field!

    public Name(String name)
    {
        this.name = name;  // this.name is a String field
    }

Leave a Comment