Java Reference
In-Depth Information
public class Radio
{
public int volume;
public double channel;
public char band;
public Radio(int v, double c, char b)
{
volume = v;
channel = c;
band = b;
}
}
public class ToStringDemo
{
public static void main(String [] args)
{
Radio radio = new Radio(7, 100.3, 'F');
System.out.println(“toString returns “ + radio.toString());
System.out.println(“Just printing the reference: “ + radio);
}
}
Figure 6.2 shows the output of the ToStringDemo.
The toString() method invoked on the radio object created the following
String:
Radio@1ea2dfe
The output of printing out the reference generated the same String:
Just printing the reference: Radio@1ea2dfe
The toString() method was invoked implicitly by the JVM when the reference
was concatenated with a String.
When the radio reference is concatenated to the string “Just printing the
reference: “, the reference needs to be converted to a String before the
concatenation can occur. Notice that the toString() method is invoked
automatically. Because every object in Java is a child of Object, every
object has a toString() method, and the JVM will invoke toString()
implicitly anytime the object needs to be converted to a String.
Figure 6.2
The output of the ToStringDemo program.
Search WWH ::




Custom Search