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;
}
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.
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 ?
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.