[英]About overriding toString() method in Java
I am watching a video that is trying to override the toString() method in Java, as following我正在观看一段视频,该视频试图覆盖 Java 中的 toString() 方法,如下所示
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.看来这里的
toString()
仍然是 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.如果
items
是另一个 class 的数组,则此行从另一个 class 调用toString()
。 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
).如果
items
是当前 class 的数组,则当array.length == 0
时递归将停止,或者将是无限递归(这将引发StackOferflowException
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.