using this as String reference
Hi friends,
Can anybody help find my mistake in the following code.?
_
public class ThisCheck
{ public ThisCheck()
{System.out.printf("%s",this);
}
public String str()
{return "shiva";
}
public static void main(String a[])
{ ThisCheck the=new ThisCheck();
}
}
__
the output I am expecting is Shiva.
But the output Iam getting is the address of the object ThisCheck
as ThisCheck@7d772e
What's going wrong?
I appreciate ur help.
[550 byte] By [
shiva7a] at [2007-10-3 4:15:07]

Where do you think you're invoking the "str" method?
When you invoke printf, it is implicitly invoking the toString method, which you haven't supplied, so it's using the original implementation of that method.
What made you think it would magically invoke your homemade "str" method?
Try:public class ThisCheck {
public ThisCheck() {
System.out.printf("%s", this);
}
public String toString() {
return "shiva";
}
public static void main(String a[]) {
ThisCheck the = new ThisCheck();
}
}
The %s flag in printf() looks for the toString() method of the corresponding
argument. (Details here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html)
When you post it's a good idea to use the Formatting tips
http://forum.java.sun.com/help.jspa?sec=formatting
Basically it means putting [code] at the start of your code and [/code] at
the end.
> I didn't know that it should strictly be toString()
> method.
> I thought any method name that returns a string .
You can certainly provide any method you want that returns a String, and use it however you want. But if you're doing this: System.out.println(myObject);
then how can it know which of your methods it should call? The reason you use toString here is because println calls toString.
jverda at 2007-7-14 22:16:34 >
