Java Reference
In-Depth Information
To make it print better, you should provide an implementation of toString() that prints the
class name and some of the important states in all but the most trivial classes. This gives you
formatting control in println() , in debuggers, and anywhere your objects get referred to in
a String context. Here is the previous program rewritten with a toString() method:
public
public class
class ToStringWith
ToStringWith {
int
int x , y ;
/** Simple constructor */
public
public ToStringWith ( int
int anX , int
int aY ) {
x = anX ; y = aY ;
}
@Override
public
public String toString () {
return
return "ToStringWith[" + x + "," + y + "]" ;
}
/** Main just creates and prints an object */
public
public static
void main ( String [] args ) {
System . out . println ( new
static void
new ToStringWith ( 42 , 86 ));
}
}
This version produces the more useful output:
ToStringWith[42,86]
See Also
This example uses String concatenation, but you may also want to use String.format()
or StringBuilder ; see Chapter 3 .
To avoid having to write all the code in a toString method, have a look at the Apache Com-
mons ToStringBuilder .
Search WWH ::




Custom Search