Google+

205. Using toString( ) method of Object Class to print values of the object









Pre-requisite -



As Object Class is the super class of all the Classes in Java. All the method of Object Class like toString( ) method are inherited by all the Classes in Java.

In order to print the values of the object instead of printing the ClassName followed by hash code in the output, we have to first override the inherited toString( ) method of the object's Class.

In the overridden method of toString( ), we have to return the values of the object.

Example of the overridden method -

The following method will override the original Object Class toString( ) method.

public String toString( )
{
      return "The value of the instance variable var1 of the object is "+var1 ;
}

Since we are returning the String, the return type is String.


Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, open the Java Project created in our previous post 'Project 34' for printing the object using toString( ) method as shown below -



2. In 'ClassOne' Class, create a method toString( ) to override the original toString( ) method of Object Class -


3. Now save& run the Java Class file 'ClassXYZ' and view the output in the console as shown below -


As both the below statements have called the toString( ) overridden method inside ClassOne Class we got this output -

  • System.out.println(object1); //Called the overridden method toString( ) inside ClassOne class
  • System.out.println(object1.toString( )); //Called the same overridden method toString( ) inside ClassOne class.

In the overridden method toString( ), we have clearly specified to return "The value of the instance variable var is "+var1 . Hence we got the above output.

So this is how we can use the toString( ) method of Object class.





Please comment below to feedback or ask questions.

Using getClass( ) method of Object Class will be explained in the next post.





No comments: