Thread: toString method
View Single Post
  #2 (permalink)  
Old 01-30-2008, 08:18 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,266
hardwired is on a distinguished road
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:
Code:
public String toString() { return getClass().getName() + "[n1:"+n1+", d1:"+d1+", n2:"+n2+", d2:"+d2+"]"; }
You use/test this inside your main method like this:
Code:
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.
Reply With Quote