I was wondering what people put into their toString() methods in Java.
I have been adding a few to some new classes and was wondering if it should include the classname or not.
In the class ClassConfig
I cant开发者_Go百科 decide if I should have
@Override
public String toString() {
return "ClassConfig:" + name; //frozen
}
or
@Override
public String toString() {
return name; //frozen
}
Neil
This is really case to case problem. If your intention is to debug, then I guess including class name is much better.
I would, besides field values, include both class name and field names. Maybe even call super.toString()
.
Like in:
@Override
String toString() {
return "ClassConfig{" +
"name=" + name +
"} " + super.toString();
}
That depends highly on whether it makes sense to have your class be represented as a String or not. If it makes sense, have it return a String that can be used, the classname won't be very useful in that case. If the String representation is likely to never get used for something, put the classname, some current states of the variables and whatever you like into it.
That's up to you to put what you want in toString(). Usually, the toString() is made and used to make readable an object. By default toString() displays an unreadable computer address.
For example, many people will implement a class Price like this:
public class Price {
private double price = 10.0;
private String ccy = "€";
@Override
public String toString() {
return price + " " + ccy; //will display "10.00000000 €"
}
}
You can make the toString() method return anything you like. I have never overridden toString() to return the class name so far.
I would personally like to put the class name as well as the key attributes in the in the class to be printed which is useful during debugging.
精彩评论