Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to add tostring

 
John Cu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic