It's common when creating your own classes that you might wish
to have a string representation of an object.
In other words, you might need to convert your object into a
String. This can be helpful when you are using a framework or
other technology that displays objects. For example, in JavaFX
you can display a list box that contains a collection of objects.
The list box will automatically display the string representation
of each object.
Adding this feature to your objects is done by adding a
toString() method to your class.
Adding the toString() Method
What should the string representation of an object look like?
That would be up to the designers of the class: often the string
version of an instance contains the state of
the object (the contents of all the object's data members).
Other times it might contain only some of the state, or it might
contain something else entirely. There's no single correct
answer, although showing an object's state is the most common.
For example, a Course class
might have the toString() defined to return the course code followed by
a colon and the course name, e.g. "CHOC101: Introduction to Chocolate".
Why "toString" ?
Interestingly, the toString() method is already defined in Java
to return a "string representation" of an object. If you're familiar
with Inheritance, the toString() comes from the class called
Object. If you're not yet familiar with Inheritance,
don't worry - you'll learn more about this later. It's enough to
understand that it's already part of Java, so it has to look and
behave a specific way.
When you add your own toString() method to your classes, it must
always be defined as:
public String toString() { ... }
Your toString() method must return a String object.
For example, the toString() method for the Course class might be defined as:
In designing a class, you need to think of what the instances of your classes
should "look like" as Strings. Then you can define an appropriate
toString() method.
As an example, let's use this Circle class:
public class Circle {
private double radius = 1.0;
public Circle() {}
public Circle(double radius) {
init(radius);
}
private void init(double radius) {
setRadius(radius);
}
public void setRadius(double radius) {
if (radius > 0) {
this.radius = radius;
} else {
throw new IllegalArgumentException("Radius must be greater than 0.");
}
}
public double getRadius() {
return radius;
}
public double calcCircumference() {
return 2 * Math.PI * radius;
}
public double calcArea() {
return Math.PI * radius * radius;
}
}
Our design team decides that an instance of circle should be have a
string representation like this:
Circle: radius=r.r
...where r.r is the circle's radius, formatted to 1 decimal place.
We might then add the toString() as follows:
public class Circle {
private double radius = 1.0;
public Circle() {}
public Circle(double radius) {
init(radius);
}
private void init(double radius) {
setRadius(radius);
}
public void setRadius(double radius) {
if (radius > 0) {
this.radius = radius;
} else {
throw new IllegalArgumentException("Radius must be greater than 0.");
}
}
public double getRadius() {
return radius;
}
public double calcCircumference() {
return 2 * Math.PI * radius;
}
public double calcArea() {
return Math.PI * radius * radius;
}
public String toString() {
return String.format("Circle: radius=%.1f", radius);
}
}
Implicit Call to toString()
When your class has a toString() method, it allows you do print objects
to the console using print() or println() in this way:
Circle circleObject = new Circle();
System.out.println(circleObject);
In this example, the println() method will look inside the circle for
a toString() definition. If it finds one, it will execute that method,
take the String object that method returns, and send that String to the
println() method. This will show your toString() method's return value
on the console.
If you don't have a toString() in your class, Java will use the default
toString() definition. The default toString() method returns a String
that consists of the name of the class that the object is an instance
of, the @ symbol, and then the objects hash code in hexadecimal form.
For example, if your circle class didn't have a toString(), then the
previous code segment might print something like:
Circle@82ba41
(You can test this out by commenting out our Circle's toString() and then
trying to print a circle instance in a println() statement.
You can see how unhelpful the default toString() is, which is why many
classes include their own toString() methods!