Jump to content

  • Log In with Google      Sign In   
  • Create Account

#ActualShaquil

Posted 24 May 2013 - 06:17 AM

I'm going through a Java book, and the author mentioned that anytime I try to convert an object to a string, the compiler will call that object's toString() method. Example:

 

 

ExampleObject A = new ExampleObject();//toString() is not overridden in the class definition

System.out.println("to String = " + A);//What is going to happen now?
 

 

 

Although in his example, he did override the toString() method in his class, he never says what'll happen if I don't do that. Looking online a bit, I couldn't find an answer, but it is clear that even if toString() is not overridden it will be called, will return a string, and the compiler won't yell at me. So what exactly is going on? Also, could anyone explain why in god's name this was a good idea to build into the language?


#1Shaquil

Posted 24 May 2013 - 06:17 AM

I'm going through a Java book, and the author mentioned that anytime I try to convert an object to a string, the compiler will call that object's toString() method. Example:

 

ExampleObject A = new ExampleObject();//toString() is not overridden in the class definition

 

System.out.println("to String = " + A);//What is going to happen now?

 

Although in his example, he did override the toString() method in his class, he never says what'll happen if I don't do that. Looking online a bit, I couldn't find an answer, but it is clear that even if toString() is not overridden it will be called, will return a string, and the compiler won't yell at me. So what exactly is going on? Also, could anyone explain why in god's name this was a good idea to build into the language?


PARTNERS