Neil Wightman
Neil Wightman

Reputation: 1133

Java toString() - Do you include the classname in the toString?

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

Upvotes: 3

Views: 2877

Answers (6)

xor_eq
xor_eq

Reputation: 4073

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.

Upvotes: 3

java_mouse
java_mouse

Reputation: 2109

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.

Upvotes: 0

Nebril
Nebril

Reputation: 888

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

Upvotes: 3

Eric V
Eric V

Reputation: 1170

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

}

Upvotes: 1

Akku
Akku

Reputation: 4454

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

Upvotes: 0

nanda
nanda

Reputation: 24788

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

Upvotes: 4

Related Questions