Object class of Java is having predefined toString() method. This method by default Object class calls implicitly when an object created. Overriding toString manually is nothing but implementing this method in our class.The java toString() method is used when we need a string representation of an object. It is defined in Object class.
The toString() method is useful for debugging. By default, when an object is printed out in a print stream like System.out, the toString() method of the object is automatically called.
While develping the code the developers used to check the object properties are getting through the object or not. For this print statement will be useful to quick test in the console.
Let us take a Person class and try to print the person object using the System.out.println() statement.
package
blog.javabynataraj;
class
Person{
public
String fname;
public
String lname;
Person(String fn,String ln){
this
.fname=fn;
this
.lname=ln;
}
public
String getFname() {
return
fname;
}
public
void
setFname(String fname) {
this
.fname = fname;
}
public
String getLname() {
return
lname;
}
public
void
setLname(String lname) {
this
.lname = lname;
}
}
public
class
ToStringTest {
public
static
void
main(String[] args) {
Person p =
new
Person(
"murali"
,
"dhar"
);
System.out.println(p);
}
}
package
blog.javabynataraj;
class
Person{
public
String fname;
public
String lname;
Person(String fn,String ln){
this
.fname=fn;
this
.lname=ln;
}
public
String getFname() {
return
fname;
}
public
void
setFname(String fname) {
this
.fname = fname;
}
public
String getLname() {
return
lname;
}
public
void
setLname(String lname) {
this
.lname = lname;
}
public
String toString(){
return
(getClass()+
" FirstName: "
+fname+
" LastName: "
+lname);
}
}
public
class
ToStringTest {
public
static
void
main(String[] args) {
Person p =
new
Person(
"murali"
,
"dhar"
);
System.out.println(p);
}
}
See the output of this:
Now you can achieve this by overriding the default toString() method inside Person class to return the contents of the instance of Person.
http://javabynataraj.blogspot.in/2012/10/importance-of-tostring-in-java.html
No comments:
Post a Comment