-
Wouldn’t it be nice to be able to output objects that you have made using the simple line System.out.print(Object name)? Let’s consider the example of the RegularPolygon class discussed in Lesson A6. It would be nice to be able to print out the statistics of your RegularPolygon objects without having to do a lot of System.out.print statements. Thanks to the toString method, you have the ability to do this.
- You can create a toString method in any of your classes in the format of public String toString(). Within the toString() method, you can format your class variables into one String object and return that String. Then, when Java encounters your Object in a String format, it will call the toString() method. Let’s look at an example using a RegularPolygon class.
public String toString()
{
String a = "Sides: " + getSides();
a += " Length: " + getLength();
a += " Area: " + getArea();
return a;
}
RegularPolygon square = new RegularPolygon(4, 10);
System.out.println(square);
Run Output:
Sides: 4 Length: 10 Area: 100
- You must be careful when using this, because you are fixing the format of the output. Oftentimes, you will still want to format your output depending on the specific problem you are solving, but the
toString()
method provides a simple and quick way to look at the state of your objects. There are also many times when the toString()
method will be very useful. Consider a Student class that contains member variables for first name, middle name, last name, a list of classes being taken, the student’s address and phone number, etc. You could easily make a toString()
method that would simply output the students first name, middle initial, and last name for quick reference. Every time you design a class, you should stop and think about whether or not your class would benefit from having a toString()
method and how you should format this String
.