0

I've got two classes, below. When I run the class TestSimple, it prints out "blueblueblue is blue repeated". That print statement is executed as System.out.println(item) which is an instance of the Simple() class. I've never seen an object print out as a phrase before, and I'm having a hard time pinning down why this is happening.

I see that there is a method in the Simple class called toString which should print this out when it is called, but I don't see that method called anywhere. What's going on here?

public class Simple {
     private String word; 
     private String phrase; 
     public Simple(int number, String w) {  
          word = w;     
          phrase = mystery(number, w);          
     }   
     private String mystery(int num, String s) {    
          String answer = "";   
          for (int k=0; k<num; k++) {       
               answer = answer + s;     
          }     
          return answer; 
     } 

     public String toString() {     
          return phrase + " is " + word + " repeated";
     }
}

And

public class TestSimple{
     public void print() {      
          Simple item = new Simple(3, "blue");      
          System.out.println(item);         
     }      

     public static void main(String[] args) {
        new TestSimple().print();
    }
}
rocksNwaves
  • 5,331
  • 4
  • 38
  • 77

1 Answers1

2

System.out is a PrintStream, PrintStream.println(Object) (from the linked Javadoc) calls at first String.valueOf(x) to get the printed object's string value and String.valueOf(Object) returns the value of obj.toString()

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249