public class example
{
private String one;
private String two;
public example(String one, String two)
{
this.one = one;
this.two = two;
}
public static void main(String[] args)
{
System.out.println(returning());
}
public static example returning()
{
return new example("yes", "no");
}
public String toString()
{
return one + " SPACESPACESPACE " + two;
}
}
run:
yes SPACESPACESPACE no
BUILD SUCCESSFUL (total time: 3 seconds)
I was trying to learn how constructors work, and I wrote some code that had a toString
method. I called System.out.print
on the returning()
function, and it printed "yes SPACESPACESPACE no" which is only found in the toString
method. However, I never had an object for the toString
method to act on (namely objectCreatedFromClass.toString()
), so I never actually used the toString
method.
Can someone explain to me why this happened? Why was I allowed to return a new object, namely return new example("yes", "no")
when my class
is a static method?
System.out.println
turns objects into strings that it can print out?Object.toString()
.