Re: question about the toString Method
Art Cummings wrote:
Hello everyone,
I've been trying to understand how the toString Method works. I've been
looking at this during the semester break so the instructor hasn't been
available for questions. Specifically i'm trying to understand why the
System.out.println method calls the toString method in my Course class.
I've included the bare minimum, that I think is necessary to understand the
question i'm asking. I omitted the Textbook and Instructor classes. What's
confusing me is why there seems to be nothing in the calling statement to
direct the flow of the program to the toString method in the Course class.
....
// Create a Course object.
Course myCourse =
new Course("Intro to Java", myInstructor,
myTextBook);
// Display the course information.
System.out.println(myCourse); **************WHY DOES THIS CALL THE
toString method in the Class course?****************
}
}
....
public String toString() *********************** WHY IS THIS CALLED
BY System.out.println?****************************
This is really a question about PrintStream's println method with an
Object argument. See its API documentation at e.g.
http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#println(java.lang.Object)
It refers to the corresponding print method's documentation.
The print method's documentation says "Print an object. The string
produced by the String.valueOf(Object) method is translated into bytes
according to the platform's default character encoding, and these bytes
are written in exactly the manner of the write(int) method."
That links to the String.valueOf(Object) documentation which says
'Returns: if the argument is null, then a string equal to "null";
otherwise, the value of obj.toString() is returned.'
Therefor System.out.println(myCourse) calls myCourse.toString().
Patricia