i have a simple doubt about the tostring() method,just consider this example
public class BobTest
public static void main (String args)
Bob f = new Bob("GoBobGo", 19);
Bob(String nickName, int shoeSize)
this.shoeSize = shoeSize;
this.nickName = nickName;
public String toString()
return ("I am a Bob, but you can call me " + nickName +". My shoe size is " + shoeSize);
the output of this program is "I am a Bob, but you can call me GoBobGo. My shoe size is 19"
i dint understand that how this program invoked the toString() method, it has no reference in the main method also? is it invoked automatically? how does it works? please explain?
toString is a method of class "object"
every class we create implicitly extends the object class hence every class have a toString method
whenever you write System.out.println(xyz) it invokes the toString method
here you are overriding toString hence due to polymorphism the toString method you declared in the program is invoked and gives the output
Joined: Mar 24, 2009
thanks!thank you very much for replying!
So you are trying to tell that all the method which are present in the Object class are invoked automatically ?
and here in my example System.out.println(f); is responsible for the invocation of the toString() method? am i right?how does polymorphism comes into play here?
vijay umar wrote:how does polymorphism comes into play here?
here if you dont override the toString method the System.out.println will call the original toString method inherited from the object class
but since you have overridden it that's why the overridden toString method will be called.
Answer to your question, " here in my example System.out.println(f); is responsible for the invocation of the toString() method? am i right?how does polymorphism comes into play here? "
Javadoc of Print says,
public void print(Object obj)Print an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
public static String valueOf(Object obj)Returns the string representation of the Object argument.
obj - an Object.
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
That's why when you do System.out.print(f) where f is your obejct, toString method gets invoked.
i have small clarification to be made on avi's post!
you said that if we dont override toString() method then it will be called automatically!
i did like that and i got the object in some form of@@$$gobobgo, it is byte form i suppose, but what i read in books is that toString() is used to convert the object into String format! is'nt it! so when it is called automatically when i havent overriden it then it should give me the string value as gobobgo and 19 as output isnt it!!