简体   繁体   中英

About overriding toString() method in Java

I am watching a video that is trying to override the toString() method in Java, as following

And I am curious about this line of code:

returnString += items[i].toString();

It seems that the toString() here is still the one of Object class.

Why won't this line result in a recursion of the new method I am defining?

That is to say, how do I know which method would it be for the method written inside a new method I am trying to override?

@Override
public String toString() {
    String returnString = "{";

    for (int i = 0; i < size-1; i += 1) {
        returnString += items[i].toString();
        returnString += ", ";
    }
    returnString += items[size-1];
    returnString += "}";
    return returnString;
}

If items is array of another class so this line calls to the toString() from the other class. If items is an array of current class, the recursion will stop when the array.length == 0 or will be an infinity recursion (that will throw an StackOferflowException ).

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