Why toString() works? We didn't call it. It works like a constructor.
public class Main {
public static void main(String[] args) {
// write your code here
A a=new A();
System.out.println(a);
}
}
class A{
@Override
public String toString(){
return "Hello";
}
}
what about we will delete println
, make breakpoint and run the program in debug mode?
public class Main {
public static void main(String[] args) {
A a=new A();
A a2=a;
}
}
class A{
@Override
public String toString(){
return "Hello";
}
}
as we can see, "Hello" sets to a
and a2
.
Why??
When you're debuging code in Java (and many other languages), the IDE evaluates expressions using built-in methods of the same language. The default representation of the object for IDE usually the string representation.
The debugger calls toString
method to obtain something to show in variables and since you've overiden it, the debugger shows you Hello
instead default description of the object (which is the default implementation of toString
in the class Object
).
According the java.lang.Object
source code, the implementation:
177: /**
178: * Convert this Object to a human-readable String.
179: * There are no limits placed on how long this String
180: * should be or what it should contain. We suggest you
181: * make it as intuitive as possible to be able to place
182: * it into {@link java.io.PrintStream#println() System.out.println()}
183: * and such.
184: *
185: * <p>It is typical, but not required, to ensure that this method
186: * never completes abruptly with a {@link RuntimeException}.
187: *
188: * <p>This method will be called when performing string
189: * concatenation with this object. If the result is
190: * <code>null</code>, string concatenation will instead
191: * use <code>"null"</code>.
192: *
193: * <p>The default implementation returns
194: * <code>getClass().getName() + "@" +
195: * Integer.toHexString(hashCode())</code>.
196: *
197: * @return the String representing this Object, which may be null
198: * @throws OutOfMemoryError The default implementation creates a new
199: * String object, therefore it must allocate memory
200: * @see #getClass()
201: * @see #hashCode()
202: * @see Class#getName()
203: * @see Integer#toHexString(int)
204: */
205: public String toString()
206: {
207: return getClass().getName() + '@' + Integer.toHexString(hashCode());
208: }