I have a class:
public class Foo {
...
}
I know if I don't override the toString() method & do following, it would print out the address of the instance of Foo:
Foo foo = new Foo();
System.out.println(foo); // this prints the address of foo
But if I override the toString():
public class Foo {
...
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("My customized string.");
return builder.toString();
}
}
same code would print out the string defined in the customized toString() method:
Foo foo = new Foo();
// this prints the "My customized string."
System.out.println(foo);
What I want to achieve is to printout both the address and the customized string, I tried following:
public class Foo {
...
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("My customized string.");
// return adress and the customized string
return this + ", " + builder.toString();
}
}
But got exception:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:698)
at java.lang.StringBuilder.append(StringBuilder.java:214)
How can I print out both address and the customized string when calling System.out.println(foo)
?