views:

85

answers:

5

Hi All.

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 decide if I should have

@Override
public String toString() {
    return "ClassConfig:" + name; //frozen
}

or

@Override
public String toString() {
    return name; //frozen
}

Neil

A: 

This is really case to case problem. If your intention is to debug, then I guess including class name is much better.

nanda
Especially with debugging (with an IDE), including the class name into toString() is pretty useless since your IDE will provide you with the classname.
f1sh
except if he doesn't know how to debug and console is the way he debugs. Nothing's wrong with that. We've been there before, haven't we?
nanda
What if you are debugging your application based on the stuff that got written to a log file? I completely disagree that `toString` methods are useless.
Stephen C
+2  A: 

That depends highly on weather 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.

xor_eq
A: 

You can make the toString() method return anything you like. I have never overridden toString() to return the class name so far.

Akku
Then you haven't been programming Java very long :-) (Besides, the OP is talking about **including** the class name.)
Stephen C
Guess I'm just able to use a debugger.
Akku
A: 

Hello Neil!

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 €"
      }

}

Eric V
+2  A: 

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();  
}
ghaxx