You can teach an Object how to print itself simply by saying its name. Continue reading to find out how this is done.
*The ToString method is used in the following example under “Serializable.”
The ToString() could quite possibly be the most useful method I have ever used because it is the most versatile and is handy for debugging.
It uses the following syntax:
public String ToString(){
return ;
}
This method is called when asked to print an Object. To include, it allows you to specify what is to be printed when the object is called.
Unlike any other type of method, this method is implied, and it is not necessary to add .toString() on the end of the object.
All spellings of the toString are as I have laid them out. It NEVER takes any parameters, and only returns a String. Simple calculations can be done beforehand, but if at all possible, stylistically this is not the place for them.
CODE example:
public class ToStringExample{
public static class Objects implements java.io.Serializable{
String text;
public Objects(){
text = “William. §”;
}
public Objects(String s){
text = s;
}
public String toString(){
return text;
}
}
public static void main(String args[]){
//create an object initialized by the constructor
Objects o = new Objects();
System.out.println(o); //the output is William. § since that is the text provided in the default constructor.
//create another object initialized with text supplied
Objects o2 = new Objects(“Wilson”);
System.out.println(o2); //the text within the object o2 is Wilson since we supplied it
}
}
Check out the example within Constructors, and notice that the .text is now missing. It is not necessary to tell the Objects o and o2 what to print as they know how to print themselves with the toString() method.
*Keep Programming*
Questions/Comments: [email protected]
-William. § (marvin_gohan)