I just started learning Java. What I've learned about constructor is that :
It will automatically run when an object is initialized.
The name of the constructor has be the same as the class name.
Now, below is where I'm starting to get confused.
class Frog{
public String toString() {
return "Hello";
}
}
public class App {
public static void main(String[] args) {
Frog frog1 = new Frog();
System.out.println(frog1);
}
}
My question :
Since public String toString ()
is not a constructor, then why can it behave like constructor when I run the program. I thought It can only be run when I call it from the App
class.
Short answer: public frog1.toString()
method call is used inside System.out.println(Object x)
call stack.
But how? Let's find it out together :)
Take a look at the PrintStream
class (which instance is used as System.out
field value by default) source code and its println
implementation that accepts Object
argument:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
And the String
's valueOf
method for argument with Object
type is:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
obj
is frog1
in your case, its toString()
method is called and returns "Hello"
String instance for the console output)
The "toString" is not behaving like a constructor; the reason why it is being called is the second line in your main
method:
System.out.println(frog1);
This invokes toString
on frog1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With