I was wondering exactly how the toString() method runs without being called when printing out a object.
Code visualization:
Without toString() method:
public class Shop
{
Shop()
{
}
public static void main(String[] args)
{
Shop myShop = new Shop();
System.out.println(myShop);
}
}
Result: Shop@3421
With toString() method:
public class Shop
{
Shop()
{
}
public void toString()
{
return "I am a shop";
}
public static void main(String[] args)
{
Shop myShop = new Shop();
System.out.println(myShop);
}
}
Result: I am a shop. The toString method ran but was never called? How?
>Solution :
toString does get called – just not by you! println takes an Object as its argument. As Object has a toString method (the default of which you saw when running your first snippet) the println method will call the passed Object‘s toString before putting the output into System.out.