Java Reference
In-Depth Information
The following snippet of code shows you how to use the
toString()
method of the
SmartIntHolder
class:
// Create an object of the SmartIntHolder class
SmartIntHolder intHolder = new SmartIntHolder(234);
String intHolderStr = intHolder.toString();
System.out.println(intHolderStr);
// Change the value in SmartIntHolder object
intHolder.setValue(8967);
intHolderStr = intHolder.toString();
System.out.println(intHolderStr);
234
8967
There is no special technical requirement for reimplementing the
toString()
method in your class. You need
to make sure it is declared
public
, its return type is
String,
and it does not take any parameters. The returned string
should be human readable text to give an idea about the state of the object at the time the method is called. It is
recommended to reimplement the
toString()
method of the
Object
class in every class you create.
Suppose you have a
Point
class to represent a 2D point as shown in Listing 7-6. A
Point
holds the x and y
coordinates of a point. An implementation of the
toString()
method in the
Point
class may return a string of the
form
(x, y)
, where x and y are the coordinates of the point.
Listing 7-6.
A Point Class Whose Object Represents a 2-D Point
// Point.java
package com.jdojo.object;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
/* Reimplement toString() method of the Object class */
public String toString() {
String str = "(" + x + ", " + y + ")";
return str;
}
}
The
toString()
method of a class is very important, and Java provides you with easy ways to use it. Java calls
the
toString()
method of an object automatically for you in situations when it needs a string representation of the
object. Two such situations that are worth mentioning:
•
A string concatenation expression involving a reference of an object
System.out.print()
and
System.out.println()
methods with an object reference
as a parameter
•
A call to