• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString() behaviour

 
Punya Pratap Singh
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have read the behaviour of toString(),so If I provided toString overriden version in the same class why is it not printing
"MY NAME IS TOSTRING()" instead of "MY NAME IS JAVA"
I think I have some confusion please explain.
As in case of any object Type passed in SOP it always prints what we write in toString() why ?

Thanks..


public final class ToStringOperations {


public static void main(String... aArgs){
String str = new String("MY NAME IS JAVA");
System.out.println(str);
}

@Override

public String toString() {
String str = new String("MY NAME IS TOSTRING()");
return str;
}
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The toString() of that class is called whose object is being passed. In you case you are passing a String object and hence the toString() of the String object is called. If you wanted the toString() which you have overridden to be called you should pass an object of class ToStringOperations.


And please UseCodeTags to post your source code.
 
Punya Pratap Singh
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Mohamed Sanaulla..
 
Punya Pratap Singh
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more thing if we had not given implementation of toString() in class "ToStringOperations" and we would have passed object of "ToStringOperations" class in SOP .then println had to call toString() from which class--(I thing from Object Class).
why ?
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Punya Pratap Singh wrote:One more thing if we had not given implementation of toString() in class "ToStringOperations" and we would have passed object of "ToStringOperations" class in SOP .then println had to call toString() from which class--(I thing from Object Class).
why ?


So toString() is from the Object class. If you override the method than at Runtime the overridden version is called. If not overridden then the implementation in the super class(Object) is called. And you could try removing the override and then printing to see what it prints.
 
Punya Pratap Singh
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Satisfied.
Thanks a lot Mohamed
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic