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 is since the toString()
method is not a constructor, then why does it behave like a constructor when I run the program? I thought it could only run when I called 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)