stackoverflow error in class constructor

故事扮演 提交于 2019-11-26 23:12:27

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
    }

Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!