Thursday, July 19, 2012

Why override tostring method in java ?




The toString() method in the Object class is used to display some information regarding any object.
If any code needs some information of an object of a class, then it can get it by using this method

The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method.


package com.example.generics;

public class ToStringMethodTest {
private String companyName;
private String companyAddress;
public ToStringMethodTest(String companyName, String companyAddress) {
this.companyName = companyName;
this.companyAddress = companyAddress;
}
public static void main(String[] args) {
ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
System.out.println(test.toString());
}

public String toString() {
return ("Company Name: " + companyName + "n" +
"Company Address: " + companyAddress);
}
  }

OUTPUT:

Company Name: ABC private LtdnCompany Address: 10, yy Street, CC Town

But if you comment the toString() method...you will get output below

com.example.generics.ToStringMethodTest@9304b1


What we have just now seen is just a sample of how a meaningful override of the toString() method would prove to be of great use in displaying an object’s information when we try printing an object using the System.out.println statement during debugging processs.

No comments:

Post a Comment