Java Reference
In-Depth Information
// Print the string representations
System.out.println(objStr);
System.out.println(intHolderStr);
java.lang.Object@360be0
com.jdojo.object.IntHolder@45a877
Note that your
IntHolder
class does not have a
toString()
method. Still, you were able to call the
toString()
method using the
intHolder
reference variable because all methods in the
Object
class are available in all classes
automatically.
You may notice that the string representation that is returned from
toString()
method for
IntHolder
object is
not so useful. It does not give you any clues about the state of the
IntHolder
object. Let's reimplement the
toString()
method in your
IntHolder
class. You will call the new class
SmartIntHolder
. What should your
toString()
method
return? An object of
SmartIntHolder
represents an integer value. It would be fine just to return the stored integer
value as a string. You can convert an integer value, say
123
, into a
String
object using the
valueOf() static
method
of the
String
class as
String str = String.valueOf(123); // str contains "123" as a string
Listing 7-5 has the complete code for your
SmartIntHolder
class.
Listing 7-5.
Reimplementing toString() Method of the Object Class in the SmartIntHolder Class
// SmartIntHolder.java
package com.jdojo.object;
public class SmartIntHolder {
private int value;
public SmartIntHolder(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
/* Reimplement toString() method of the Object class */
public String toString() {
// Return the stored value as a string
String str = String.valueOf(this.value);
return str;
}
}