How to use the toString() in Java ?

What is toString()?

A?toString()?is an in-built method in Java that returns the value given to it in?string?format. Hence, any object that this method is applied on, will then be returned as a?string object.

No alt text provided for this image

How to use the toString() method

The?toString()?method in Java has two implementations;

  • The first implementation is when it is called as a method of an object instance. The example below shows this implementation

No alt text provided for this image

  • The second implementation is when you call the member method of the relevant class by passing the value as an?argument. The example below shows how to do this

No alt text provided for this image

What is interesting is that this method can also be?over-ridden?as part of a class to cater to the customized needs of the user. The example below shows how to do this!

No alt text provided for this image

In the code above, from?lines 11 to 13?we have simply created a new method within the?Pet?class with the same name as the?toString()?method. On?line 20?when the?toString()?method is called, it is the class version of the method that is invoked. However as seen on?line 22, the method does not change for any other data type!

Thanks To : Edpresso Team From Educative!



要查看或添加评论,请登录

社区洞察

其他会员也浏览了