Page 552 - Introduction to Programming with Java: A Problem Solving Approach
P. 552
518 Chapter 13 Inheritance and Polymorphism
But this produces a compile-time error. Do you know why? An overriding method must have the same re- turn type as the method it’s overriding. Since the Counter class’s toString method is an overriding im- plementation of the Object class’s toString method, the two methods must have the same return type. Since the Object class’s return type is a String, the above int return type generates an error. With that in mind, this might have been your second-cut implementation for toString:
public String toString()
{
}
return count;
But this also produces an error. Why? Incompatible types. The returned value, count, is an int, and the return type is defined to be a String. The solution is to convert count explicitly to a String before returning it, like this:
public String toString()
{
}
return Integer.toString(count);
Do you understand the Integer.toString code? In Chapter 5, you learned that all primitive types have a corresponding wrapper class. Integer is one such class—it wraps up the int primitive. The Integer class’s toString method returns a string representation of its passed-in int argument. So if count is 23, then Integer.toString(count) returns the string “23.”
Quick quiz: Is the Integer class’s toString method a class method or an instance method? Look Apago PDF Enhancer
at the method call’s prefix. The method call, Integer.toString, uses a class name for the prefix. When a method call uses a class name for a prefix instead of a reference variable, you know the method is a class method. Thus, Integer’s toString is a class method.
Note that all the wrapper classes have toString methods. They all do the same thing—they return a string representation of their passed-in argument. Here are some examples:
Double.toString(123.45)
Character.toString('G')
String’s valueOf Method
: evaluates to string "123.45"
: evaluates to string "G"
There’s another way to convert primitive variables to strings. Use the String class’s valueOf method. This takes a primitive value, and returns a string. Like the wrapper toString methods described above, it’s a class method, so you must use its class name, String, as a prefix. Thus, instead of the previous method calls, you could use these method calls:
String.valueOf(123.45)
String.valueOf('G')
: evaluates to string "123.45"
: evaluates to string "G"
The valueOf method is useful if you don’t know the data type ahead of time. It works with different data types because it’s an overloaded method, and the JVM automatically selects that particular method whose parameter type matches the type of the data provided.
In addition to converting primitives to strings, the valueOf method can also be used to convert an ar- ray of vowel characters to a string. This code fragment prints the string “aeiou”:
Char[] vowels = {'a','e', 'i', 'o', 'u'};
System.out.print{String.valueOf(vowels));