Page 551 - Introduction to Programming with Java: A Problem Solving Approach
P. 551
Figure 13.3 Counter program that illustrates implicitly calling the toString method
Counter Program’s toString Method—A Detailed Analysis
Let’s revisit the toString method in Figure 13.3’s Counter program. Since the Counter class contains only one piece of data, count, there’s no need for concatenation code as part of the toString implemen- tation. Just return count’s value and that’s it. So this might have been your first-cut implementation for toString:
public int toString()
{
}
return count;
13.4 The toString Method 517
/******************************************************
*
Counter.java
Dean & Dean
This creates a counter and displays its count value.
******************************************************/
*
*
*
public class Counter
{
}
// end class Counter
private int count;
//***************************************************
public Counter(int count)
{
this.count = count;
} // end constructor
//***************************************************
public String toString() ⎫ { ⎪⎬ return Integer.toString(count); ⎪
This overrides the Object
class’s toString method. } // end toStAripngago PDF En⎭hancer
//***************************************************
public static void main(String[] args)
{
}
Counter counter = new Counter(100);
String message = "Current count = " + counter;
System.out.println(message);
// end main