-1

This is my main:

public class testMain
{
     public static void main ( String[] args )
     {
          testClass test = new testClass();
          System.out.println(test);
     }
}

This is my class:

public class testClass
{
     private String word;

     public testClass(String s)
     {
          word = s;
     }

     public String toString()
     {
          return "test";
     }

 }

When I System.out.println(testClass) "test" from the toString method is printed. Why? How is this method's return even being executed?

1 Answers1

0

When you do

System.out.println(test);

It call's toString method on object. By default it returns class name and come additional info, but you defined it in your class (you overrided default method from Object class), so in your case it returns "test"

Ilya Mezhov
  • 111
  • 4