aspose file tools*
The moose likes Java in General and the fly likes toString() behaviour Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "toString() behaviour " Watch "toString() behaviour " New topic
Author

toString() behaviour

Punya Pratap Singh
Ranch Hand

Joined: Nov 23, 2010
Posts: 80

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

Joined: Sep 08, 2007
Posts: 3056
    
  33

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.


Mohamed Sanaulla | My Blog
Punya Pratap Singh
Ranch Hand

Joined: Nov 23, 2010
Posts: 80
Thanks a lot Mohamed Sanaulla..
Punya Pratap Singh
Ranch Hand

Joined: Nov 23, 2010
Posts: 80
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

Joined: Sep 08, 2007
Posts: 3056
    
  33

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

Joined: Nov 23, 2010
Posts: 80
Satisfied.
Thanks a lot Mohamed
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toString() behaviour
 
Similar Threads
q from jiris.com
Inheritance
whether Object is a keyword?
Can we redeclare a class
Can't Get This toString Method Overridden. Why?