Overriding toString() method in Java?

Diep Thanh Tu
1 min readJan 30, 2019

--

This post is similar to Overriding equals method in Java. Consider the following Java program:

Output:
Complex@19821f

The output is, class name, then ‘at’ sign, and at the end hashCode of object. All classes in Java inherit from the Object class, directly or indirectly . The Object class has some basic methods like clone(), toString(), equals(),.. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output. For example, in the following code toString() is overridden to print “Real + i Imag” form.

Output:
10.0 + i15.0

In general, it is a good idea to override toString() as we get get proper output when an object is used in print() or println().

via geeksforgeeks

--

--