Java Reference
In-Depth Information
Formatting Objects for Printing with toString()
Problem
You want your objects to have a useful default format.
Solution
Override the toString() method inherited from java.lang.Object .
Discussion
Whenever you pass an object to System.out.println() or any equivalent method, or in-
volve it in string concatenation, Java automatically calls its toString() method. Java
“knows” that every object has a toString() method because java.lang.Object has one
and all classes are ultimately subclasses of Object . The default implementation, in
java.lang.Object , is neither pretty nor interesting: it just prints the class name, an @ sign,
and the object's hashCode() value (see Overriding the equals() and hashCode() Methods ) .
For example, if you run this code:
public
public class
class ToStringWithout
ToStringWithout {
int
int x , y ;
/** Simple constructor */
public
public ToStringWithout ( int
int anX , int
int aY ) {
x = anX ; y = aY ;
}
/** Main just creates and prints an object */
public
public static
void main ( String [] args ) {
System . out . println ( new
static void
new ToStringWithout ( 42 , 86 ));
}
}
you might see this uninformative output:
ToStringWithout@990c747b
Search WWH ::




Custom Search