The
toString method is called by the jvm and returns a string that represents the state of the class instance. The member variables of this class are of interest so we return them, like this:
public String toString() {
return getClass().getName() +
"[n1:"+n1+", d1:"+d1+", n2:"+n2+", d2:"+d2+"]";
}
You use/test this inside your
main method like this:
Fractions fractions = new Fractions();
fractions.enterData();
System.out.println("fractions = " + fractions);
fractions.add();
System.out.println("fractions = " + fractions);
In the
println statement the jvm calls the
toString method for the "fractions" instance. If you did not provide the
toString override in your Fractions class the jvm would call the
toString method of its superclass (Object) which would return the class name and a hex address of the instance in memory. You can observe this by commenting–out the
toString method and running your test again.