Why / when would it be appropriate to override ToString?
Do you need to override
ToString
? No.Can you get a string representation of your object in another way? Yes.
But by using ToString
you are using a method that is common to all objects and thus other classes know about this method. For instance, whenever the .NET framework wants to convert an object to a string representation, ToString
is a prime candidate (there are others, if you want to provide more elaborate formatting options).
Concretely,
Console.WriteLine(yourObject);
would invoke yourObject.ToString()
.
When should I override toString()?
Josh Bloch gives a good explanation in Effective Java, in item 10.
[...] providing a good toString implementation makes your class much more pleasant to use.
It really makes it easier to output debugging traces, or makes better logging messages, since you can use the object's string representation provided by toString()
directly; you don't have to manually build a string that gives the information needed on the object.
As stated in the book, you should include all the interesting information in the resulting String
. You should also document properly your method; you may document the resulting String
format or not, but you should at least document your intent (whether the format is subject to change, or not likely to change).
In the end, it is up to you (and your company's standards) to decide if overriding it in every class should be part of your habits or not. Personally, I don't override toString ()
in every classes, only in the ones which are most at risk of being used in a debuging trace.
Is it ok to override ToString() method in this case
From the documentation:
"Returns a string that represents the current object."
If you want to create a string which is a representation of the object, that is the place.
So - yes!
EDIT:
"This string representation is used in the business logic NOT for debugging purpose."
The string representation of int
is also used for business logic. The question is if that string representation is specific for that business logic, or is it just a general representation of that object, which you use in business logic.
If it specific for that specific business logic, the generation of the string suppose to be part of that business logic.
If not, but there are many optional string representations for that object, you may want to implement IFormattable
, which defines a ToString
method which gets an IFormatProvider
and format string as parameters.
Otherwise, the regular ToString
is your friend.
Why is it common practice to override the method toString() in java to print the instance variables of the class?
We could. But how will other classes, that know absolutely nothing about your subclasses with your myNewToString method, know how to print a string that textually represents, in a concise but informative way, arbitrary subclasses?
The toString method was designed to be overridden to do that. Yes, it does have default behavior but it's not very useful. Its authors wanted you to override it. Overriding it to return what's commonly practiced is more useful, but you don't have to do that. A toString method for an EmailAddress class can return
public String toString() {
return "EmailAddress{localPart = " + localPart + ", domainName = " + domainName + "}";
}
but it's usually more useful to return something like
public String toString() {
return localPart + "@" + domainName;
}
Why must I override toString method instead of just creating another method?
If you implement the toString()
method, you can do things like:
MyType myobject = new MyType();
System.out.println(myobject);
This will automatically call the toString()
method.
If you were to implement your own method, and call it newMethod()
, you would have to do this:
MyType myobject = new MyType();
System.out.println(myobject.newMethod());
You can read more details about the toString()
method here and here.
How to override toString() properly in Java?
The toString
is supposed to return a String
.
public String toString() {
return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}
I suggest you make use of your IDE's features to generate the toString
method. Don't hand-code it.
For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString
When we override the toString() method we should always return a string representation of the object?
toString is mainly used for representing things where the audience is the programmer, like debugging and logging, where we need to see some text version of an object. Use information from the object that will be useful to you when you see it in a log file or in the debugger. From Effective Java, Chapter 3, item 10:
While it isn’t as important as obeying the equals and hashCode contracts (Item 8, Item 9), providing a good toString implementation makes your class much more pleasant to use. The toString method is automatically invoked when an object is passed to println, printf, the string concatenation operator, or assert, or printed by a debugger.
The advice in the API documentation for Object#toString is:
In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
Returning null would never count as informative, and could easily be misleading. It seems like someone was using toString to do something it was never intended for.
Overriding toString method
Overriding Object.toString
is a good approach.
However, your current implementation makes a major mistake by creating a new Move
object (see below).
To call the routine (once you fix it), do exactly what you're already doing:
jcb.engineMove(move.toString());
If toString()
should only be used for debugging (as mre says) you could implement another method named getText
that does the same thing.
IMPORTANT NOTE:
You should not be creating a new Move
object inside its toString
method.
This is a very bad idea (as mentioned by others).
Your toString
method should simply build a string and return it.
Related Topics
How to Find the State of Numlock, Capslock and Scrolllock in .Net
Set Default Global JSON Serializer Settings
Shellexecute Equivalent in .Net
How to Get the Full Url of the Page I am on in C#
What's Better: Dataset or Datareader
How to Stop Flickering C# Winforms
What Is Imex Within Oledb Connection Strings
How to Get the Actual Monitor Name? as Seen in the Resolution Dialog
Awaiting Asynchronous Function Inside Formclosing Event
What Is the "Right" Way to Bring a Windows Forms Application to the Foreground
Modify Struct Variable in a Dictionary
Difference Between "Var" and "Object" in C#
Passing Data to Master Page in ASP.NET MVC
Can a Unit Test Project Load the Target Application's App.Config File
How to Get the Word Under the Cursor in Windows
Pulling Data from a Webpage, Parsing It for Specific Pieces, and Displaying It
How to Get Little Endian Data from Big Endian in C# Using Bitconverter.Toint32 Method