DEV Community

Lalit Kumar
Lalit Kumar

Posted on

If we override the toString() method with the code below, what would be the result of printing?

In java, language inheritance is done from object class directly or indirectly. The object class have some basic methods like clone(), toString(), equals(), etc. The default toString method in Object prints “class name@ hash code”. The user can override the toString() method in our class for printing the proper output of the given function.


title: "If we overrde the tostring() method with the cde belowm what would be the result of printing?"
tags: java

canonical_url: https://kodlogs.com/blog/1917/override-tostring-method-below-what-would-result-printing

Example:

For example, the following code toString is overridden to print the “Real + Imag” form.

Code:

// file name: Main.java

class Complex {

               private double re, im;



               public Complex(double re, double im) {

                               this.re = re;

                               this.im = im;

               }



               /* Returns the string representation of this Complex number.

               The format of the string is "Re + iIm" where Re is the real part

               and Im is imagenary part.*/

               @Override

               public String toString() {

                               return String.format(re + " + i" + im);

               }

}

// Driver class to test the Complex class

public class Main {

               public static void main(String[] args) {

                               Complex c1 = new Complex(10, 15);

                               System.out.println(c1);

               }

}
Enter fullscreen mode Exit fullscreen mode

Output:

10.0 + i15.0
Note:
Generally, it is a good idea to override toString() as we get proper output when an object is used in println() or in print().

Top comments (0)