Overriding the toString() method in Object class

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. The following code illustrates this,

also read:

ToStringMethodTest.java

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);
	}
}

This output seems a bit weird. If we analyze it closely, we can find that the output is nothing but the Class name ToStringMethodTest and then the ‘@’ symbol is followed by 18d107f which is the hashcode of the object.

In case we would like to display some meaningful details of an object, we can override the toString() and thereby achieve it. Consider the following code,
ToStringMethodTest.java

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);
	}

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

The result of the above code is,

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

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 process.

also read:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>