• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how toString() works in this program???

 
n.chenththuran
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class BobTest {
public static void main (String[] args) {
Bob f = new Bob("GoBobGo", 19);
System.out.println(f);
}
}
class Bob {
int shoeSize;
String nickName;
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);
}
}

----------------------------------------------

in our main method i have not called the toString() method . But itis called with out my knowledge and the message is printed as" i am bob but u can call mehashaa and my shoe size 5" ...how it happens???
 
Fletcher Estes
Ranch Hand
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println() automatically calls the toString method on any object passed to it.
 
Vijayendra V Rao
Ranch Hand
Posts: 195
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All classes automatically inherit the toString( ) method of the Object class. So, whenever you try to print out an object, the toString() method will be called by default. The only difference is, if you have overrided that method, then your custom toString() method will be called or else, the default toString() method of the super class, Object, will be called.

If you wish to know more about this toString( ) method, then you should surely read this.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic