Re: question about the toString Method
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 27 Dec 2007 14:46:20 -0500
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.
[...]
System.out.println(myCourse); **************WHY DOES THIS CALL THE toString method in the Class course?****************
First, println() is not one method but a whole family of
methods of the PrintStream class. There's a println() method
that takes an int argument, another that takes a double, yet
another that takes no argument at all. The particular one
you're calling is the println() that takes an Object.
So, what does the println(Object) method of PrintStreamClass
do? First thing, right off the bat, is it calls the static
String.valueOf() method on the same object, and from that it
gets a String which it then prints. Like println() itself,
String.valueOf() has many versions for many argument types, and
the one we wind up with is String.valueOf(Object).
Over to the String class; what does String.valueOf(Object)
do? It depends: If the argument is null it just returns the
four-character String "null". Otherwise -- ta-daaah! -- it
calls the object's own toString() method to get a String, and
that's where the call to Course's toString() method comes from:
You call
System.out.println(myCourse), which calls
String.valueOf(myCourse), which calls
myCourse.toString(), which returns a String to
String.valueOf(myCourse), which returns the same String to
System.out.println(myCourse), which then calls
System.out.print(theString), which returns to
System.out.println(myCourse), which eventually returns to
You.
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.
- Follow-Ups:
- Re: question about the toString Method
- From: Art Cummings
- Re: question about the toString Method
- References:
- question about the toString Method
- From: Art Cummings
- question about the toString Method
- Prev by Date: Re: question about the toString Method
- Next by Date: Re: question about the toString Method
- Previous by thread: Re: question about the toString Method
- Next by thread: Re: question about the toString Method
- Index(es):