This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes how to add tostring Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to add tostring" Watch "how to add tostring" New topic
Author

how to add tostring

John Cu
Greenhorn

Joined: Oct 31, 2001
Posts: 2
I don't know how to use tostring in my program

(edited by Cindy to format code)
[This message has been edited by Cindy Glass (edited October 31, 2001).]
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
John
Are you saying you have to override the toString method?? Basicaly the toString method is a way for your class to print itself in an understandable way. If you don't override it then you'll get the Object.toString method (if your class directly inherits from Object) which just prints out the class name and the memory location - not very helpfull!!
To override toString just add a method in your class with a signature like this:

Inside of the method just have it create a string that displays whatever pertinent information you think the user might need. You can create a String and keep adding to it then return it or create a StringBuffer and add to it then return it as a String. Since you only have 3 members in the class your output might look something like this:

or something similar. In the toString you just have to create the code to produce a String that would print that (or whatever you like) and return it.
Then whenever someone trys to print an object of type MoveCat the toString method is called automatically and the string you created in that method is returned and printed.
hope that helps

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform


Dave
 
jQuery in Action, 2nd edition
 
subject: how to add tostring
 
Similar Threads
Testing classes
compile error
help
Unexpected Signal : EXCEPTION_FLT_DIVIDE_BY_ZERO
String, read and write file problem...